Hibernate Annotations Example

Hibernate Annotations Example thumbnail
10K
By Dhiraj 26 February, 2017

Defining hibernate metadata using annotations is very common and there are lot of hibernate annotations available. This article will cover hibernate annotations that are required to get started with hibernate. We will be creating a simple hibernate annotations example and discuss about different annotations used in the example along with their functionalities. We will also discuss about using enums in model class using @Enumerated annotation. All the hibernate entities related configurations will be annotation based. So, lets get started.

Different Hibernate Annotations

First we will go through different hibernate annotations and then create an example using these annotations. In the below model class there are many annotations used. In this section we will go through each and every annotations in detail.

@Entity - The use of the @Entity annotation before the declaration of a class specifies that the Java class is a hibernate entity bean. Here Employee.java is our entity bean.

@Table - It is used to provide the name of the table. In our case, the table name is EMPLOYEES. If it is ommitted, then the entity is mapped to the default schema with the same name as entity class. Inside this annotation, you can also define other parameters like catalog, indexes, schema, uniqueConstraints.

@Id - @Id annotation marks a field as a primary key field and the allowed data type can be any Java primitive type, primitive wrapper, String, java.util.Date, java.sql.Date, BigDecimal or BigInteger.

@GeneratedValue - This indicates that the specified column value will be automatically generated by the persistence provider. The allowable GenerationType can be auto, Identity, Sequence or table.

@Column - It is used to map a persisted field to table column and provides various parameters such as name, unique, nullable, insertable, updatable and column definition.

If insertable parameter is set to false, then the specified field or property is not included in the insert statement.

If the updatable parameter is set to false, then the field or property of an entity can not be updated in the db.

@Enumerated - @Enumerated indicates that the fields persistent property should be stored in the form of an Enumeration. The possible values of EnumType can be ORDINAL or STRING.

Ordinal returns its position in its enum declaration like 0, 1, 2. If the value of the field provided is set to EnumType.STRING as above, then the String value of EmployeeType is saved in the DB.

@Lob - @Lob stands for Large Object and it can be either BLOB(Binary Large Object) or CLOB(Character Large Object).

If the data is of the char[] or String type then the persistent provider maps the data to a CLOB column, otherwise the data is mapped to BLOB column.

@Temporal - The DATE, TIME and TIMESTAMP can be used to map a temporal type. If no values is specified for the TemporalType parameter of the @Temporal annotation, the TIMESTAMP is selected as default value.

Environment Setup

1. JDK 7 2. Hibernate 4 3. Intellij Idea/ eclipse 4. Maven

Project Structure

We have defined a model class - Employee.java that will represent the database table and Application.java has a main method that will be used to start the application. Here the hibernate.cfg.xml file is under hibernate directory.

hibernate-annotation-project-structure

Maven Dependencies

Following are the maven dependencies required to include in pom.xml to get started.

pom.xml
<dependencies>
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-core</artifactId>
		<version>4.3.11.Final</version>
	</dependency>
	
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.38</version>
	</dependency>
	
	<dependency>
		<groupId>org.javassist</groupId>
		<artifactId>javassist</artifactId>
		<version>3.18.0-GA</version>
	</dependency>
	
</dependencies>

Defining hibernate.cfg.xml


<hibernate-configuration>
   <session-factory>
   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">root</property>
   <property name="hibernate.hbm2ddl.auto">update</property>
   <property name="show_sql">false</property>
   <mapping class="com.devglan.model.Employee"/>
</session-factory>
</hibernate-configuration>

Following is the enum class

EmployeeType.java
package com.devglan.model;

public enum EmployeeType {
	EMPLOYEE,MANAGER,DIRECTOR;

}

Now let us define our model class which will include different hibernate annotations and then we will be discussing more about these annotations.

Employee.java
 
package com.devglan.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "EMPLOYEES")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "RECORD_ID")
	private Integer id;
	
	@Column(name = "NAME")
	private String name;
	
	@Column(name="AGE")
	private Integer age;
	
	@Enumerated(EnumType.STRING)
	@Column(name = "TYPE")
	private EmployeeType empType;
	
	public Employee() {
	}

	public Employee(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
	
	public EmployeeType getEmpType() {
		return empType;
	}

	public void setEmpType(EmployeeType empType) {
		this.empType = empType;
	}
}
Other Interesting Posts
Spring Hibernate Integration Example with JavaConfig
Object Relational Mapping in Java
Hibernate One to Many Mapping Example
Hibernate One to Many Relationship Example
Hibernate Many to Many Relationship Example

Defining hibernate.cfg.xml

hibernate.cfg.xml is used to define all the hibernate related properties like dialect name, url username, password etc and it is a default configuration of hibernate to name it as hibernate.cfg.xml.It is also possible to override it but it is required to let hibernate know this while creating session factory. The file is available under hibernte directory in case of our app.

Implementing CRUD using Hibernate Annotations

To create connection with the DB, we require a session first and we get a session from SessionFactory. SessionFactory is a thread safe object and it is created once per application. Following is the code to create a sessionFactory. This is included in the Application.java

public static SessionFactory getSessionFactory() {
	Configuration configuration = new Configuration().configure("hibernate/hibernate.cfg.xml");
	StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
			.applySettings(configuration.getProperties());
	SessionFactory sessionFactory = configuration
			.buildSessionFactory(builder.build());
	return sessionFactory;
}

By default, hibernate looks for hibernate.cfg.xml file on the classpath but since we have defined this file under a custom directory, it is required to tell that to hibernate. If this xml file would present on the classpath, then we dont have to pass parameter to configure() method.

Now let us define our Application.java which contains all the implementations for CRUD operations. This class has implementations to create employee, read employee, update employee and delete employee.

Application.java
package com.devglan.model;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class Application {
	
	public static void main(String[] args) {
		
		Employee emp1 = new Employee("John Doe", 22);
		emp1.setEmpType(EmployeeType.EMPLOYEE);
		
		Employee emp2 = new Employee("Bipul Kumar", 28);
		emp2.setEmpType(EmployeeType.MANAGER);
		
		createEmployee(emp1);
		createEmployee(emp2);
		
		List empList = fetchEmployees();
		for(Employee emp: empList) {
			System.out.println(emp.toString());
		}
		
		update(emp1);
		
		fetchEmployeeById(emp1.getId());
		
		deleteEmployee(emp1.getId());
		
		deleteAll();
		
		System.exit(0);
	}

	public static SessionFactory getSessionFactory() {
		Configuration configuration = new Configuration().configure("hibernate/hibernate.cfg.xml");
		StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties());
		SessionFactory sessionFactory = configuration
				.buildSessionFactory(builder.build());
		return sessionFactory;
	}

	public static Integer createEmployee(Employee e) {
		System.out.println("****************Creating Employee*************");
		Session session = getSessionFactory().openSession();
		session.beginTransaction();
		session.save(e);
		session.getTransaction().commit();
		session.close();
		System.out.println("Employee Created Successfully" + e.toString());
		return e.getId();

	}

	public static List fetchEmployees() {
		System.out.println("****************Fetching Employees*************");
		Session session = getSessionFactory().openSession();
		List employees = session.createQuery("FROM Employee").list();
		session.close();
		System.out.println("Fetched " + employees.size() + " Employees");
		return employees;

	}

	public static void update(Employee e) {
		System.out.println("****************Updating Employee*************");
		Session session = getSessionFactory().openSession();
		session.beginTransaction();
		Employee em = (Employee) session.get(Employee.class, e.getId());
		em.setName("updated" + e.getName());
		em.setAge(e.getAge());
		session.getTransaction().commit();
		session.close();
		System.out.println("Employee updated Successfully" + e.toString());

	}
	
	public static Employee fetchEmployeeById(Integer id) {
		System.out.println("****************Fetching Employee By Id*************");
		Session session = getSessionFactory().openSession();
		Employee e = (Employee) session.load(Employee.class, id);
		session.close();
		return e;
	}

	public static void deleteEmployee(Integer id) {
		System.out.println("****************Deleting Employee*************");
		Session session = getSessionFactory().openSession();
		session.beginTransaction();
		Employee e = fetchEmployeeById(id);
		session.delete(e);
		session.getTransaction().commit();
		session.close();
		System.out.println("Successfully deleted " + e.toString());

	}
	
	public static void deleteAll() {
		System.out.println("****************Deleting All Employee*************");
		Session session = getSessionFactory().openSession();
		session.beginTransaction();
		Query query = session.createQuery("DELETE FROM Employee ");
		query.executeUpdate();
		session.getTransaction().commit();
		session.close();
		System.out.println("Successfully deleted all employees.");

	}

}

Running the Application

Run Application.java as a java application and check the console output.

Conclusion

I hope this article served you whatever you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Hibernate