Hibernate Annotations Example

author-image   By Dhiraj,   26 February, 2017 3K

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.


Maven Dependencies

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


Defining hibernate.cfg.xml

   <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"/>

Following is the enum class

package com.devglan.model;

public enum EmployeeType {


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

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;

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

	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "RECORD_ID")
	private Integer id;
	@Column(name = "NAME")
	private String name;
	private Integer age;
	@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()
	SessionFactory sessionFactory = configuration
	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.

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);
		Employee emp2 = new Employee("Bipul Kumar", 28);
		List empList = fetchEmployees();
		for(Employee emp: empList) {

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

	public static Integer createEmployee(Employee e) {
		System.out.println("****************Creating Employee*************");
		Session session = getSessionFactory().openSession();
		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();
		System.out.println("Fetched " + employees.size() + " Employees");
		return employees;


	public static void update(Employee e) {
		System.out.println("****************Updating Employee*************");
		Session session = getSessionFactory().openSession();
		Employee em = (Employee) session.get(Employee.class, e.getId());
		em.setName("updated" + e.getName());
		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);
		return e;

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

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



Running the Application

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


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

If You Appreciate This, You Can Consider:

  • Like us at: Facebook or follow us at Twitter
  • Share this article on social media or with your teammates.
  • We are thankful for your never ending support.

About The Author


I am an energetic professional who enjoys the challenges involved in working with people and resolving real-time problems. Technical expertise in building highly scalable, distributed and self-healing cloud applications. Technical Skills: Java/J2EE, Spring Framework, Hibernate, Angular, Reactive Programming, Microservices, Rest APIs, Kafka, ELK, etc.

Further Reading on Hibernate

1 Spring Hibernate Integration Example Javaconfig

2 Object Relational Mapping In Java

3 Hibernate One To One Mapping Example

4 Spring Boot Mvc App With Jsp

5 Hibernate One To Many Relationship Example

6 Hibernate Many To Many Mapping Example

7 Hibernate Inheritance Example

8 Hibernate Criteria Tutorial

9 Spring Boot Hibernate 5 Example

10 Spring Data Jpa Example