Adding Hibernate DAO layer in existing Maven project

In this article, we will cover the steps required to add hibernate in an existing Maven project. We are using MySQL database as a reference here, but you can change it accordingly for other databases.

 

Here is the overview of steps:
 
1) Create employee table in database
 
2) In pom.xml, add dependencies for Hibernate and the database driver
 
3) Add DB connection settings in hibernate.cfg.xml
 
4) Create a hibernate SessionUtil class
 
5) Create Employee mapping file or annotated entity class
 
6) Create EmployeeDAO with the CRUD operations
 
 
Here are the steps in detail :
 
 

Step 1 : (Create employee table in database)

 
Let’s create an employee table in the database.
 
Here is the MySQL script for creating employee table :
 

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

 
If you are using another database, change the syntax accordingly.
 
 

Step 2: (Add dependencies for hibernate and mysql)

 
In pom.xml of your project, add the following dependencies for hibernate and MySQL :
 

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.10.Final</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.34</version>
    </dependency>

 
Now your project will have the required jars for Hibernate and MySQL driver.
 
 

Step 3: (Add hibernate.cfg.xml and update your database configurations)

 
Create a XML file hibernate.cfg.xml under src/main/resources path and add following contents.
 

If you don’t see the resources folder in your project, here are the steps to add the same manually :
 
Add missing src/main/resources folder in Maven project
 


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="hibernateSessionFactory">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
  <property name="hibernate.connection.username">user</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
<!--   <property name="hibernate.hbm2ddl.auto">create</property> -->
  <mapping class="com.topjavatutorial.dao.Employee"/>
 </session-factory>
</hibernate-configuration>

 
Modify the following elements in hibernate.cfg.xml for your database :
 
hibernate.connection.url
hibernate.connection.username
hibernate.connection.password
 
If you are using a database other than MySQL, use the corresponding dialect by modifying hibernate.dialect element.
 
 
Note that, we have commented out the hibernate.hbm2ddl.auto property . If this is set to create, it will drop and create the Employee table in database.
 
Since, we already have created the Employee table, we have commented it.
 
 

Step 4: Add SessionUtil class

 
If not already present, create a package com.topjavatutorial.dao in src/main/java.
 

Add the following SessionUtil class in it :
 

package com.topjavatutorial.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionUtil {
  
  private static SessionUtil instance=new SessionUtil();
  private SessionFactory sessionFactory;
  
  public static SessionUtil getInstance(){
      return instance;
  }
  
  private SessionUtil(){
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
        
    sessionFactory = configuration.buildSessionFactory();
  }
  
  public static Session getSession(){
    Session session =  getInstance().sessionFactory.openSession();
    
    return session;
  }
}


 
This will read the hibernate config file from resource path and create the session.
 
 

Step 5: Create Employee Entity class

 
In the com.topjavatutorial.dao package, add the Employee entity bean using @Entity annotation as follows :
 

package com.topjavatutorial.dao;

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

@Entity
public class Employee {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;
  @Column
  private String name;
  @Column
  private int age;
  
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  
}


 
 

Step 6: Create EmployeeDAO with the CRUD operations

 
In the package com.topjavatutorial.dao, let’s create a DAO class EmployeeDAO as follows :
 

package com.topjavatutorial.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class EmployeeDAO {
  
  public void addEmployee(Employee bean){
    Session session = SessionUtil.getSession();    
    Transaction tx = session.beginTransaction();
    addEmployee(session,bean);    
    tx.commit();
    session.close();
    
  }
  
  private void addEmployee(Session session, Employee bean){
    Employee employee = new Employee();
    
    employee.setName(bean.getName());
    employee.setAge(bean.getAge());
    
    session.save(employee);
  }
  
  public List<Employee> getEmployees(){
    Session session = SessionUtil.getSession();  
    Query query = session.createQuery("from Employee");
    List<Employee> employees =  query.list();
        session.close();
    return employees;
  }

  public int deleteEmployee(int id) {
    Session session = SessionUtil.getSession();
    Transaction tx = session.beginTransaction();
    String hql = "delete from Employee where id = :id";
    Query query = session.createQuery(hql);
    query.setInteger("id",id);
    int rowCount = query.executeUpdate();
    System.out.println("Rows affected: " + rowCount);
    tx.commit();
    session.close();
    return rowCount;
  }
  
  public int updateEmployee(int id, Employee emp){
     if(id <=0)  
         return 0;  
     Session session = SessionUtil.getSession();
      Transaction tx = session.beginTransaction();
      String hql = "update Employee set name = :name, age=:age where id = :id";
      Query query = session.createQuery(hql);
      query.setInteger("id",id);
      query.setString("name",emp.getName());
      query.setInteger("age",emp.getAge());
      int rowCount = query.executeUpdate();
      System.out.println("Rows affected: " + rowCount);
      tx.commit();
      session.close();
      return rowCount;
  }
}


 
This class contains implementations for Create, Read, Delete operations. You can similarly add Update operation as well.
 
This completes the steps required for integrating hibernate.
 
 
If you are using hibernate in a standalone project, you can add a class with main() method and methods in EmployeeDAO directly.
 
If you are using hibernate integration with Struts or JAX-RS or others, you can invoke these DAO methods from your corresponding action, service class etc and you should be able to connect to the database to perform select/insert/update/delete operations.
 
 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

10 comments

  1. What is the version?

  2. Hey, I need to download this code, could u pls give me the link

  3. Hello brother! Great tutorials! I am having a terrible issue following your RESTful CRUD operations using Jersey and Hibernate, where as soon as I add the hibernate dependencies to the pom.xml jersey stops working and gives me an exception: java.lang.NullPointerException even if I only implement
    the “simple RESTful service using Maven” you teach in another tutorial. Is there a sample code file I could download and look at? Thank you very much!

  4. Hi,
    I am not too firm on Hibernate, but don’t you have to close the session in the getEmployees()-method, too?
    Great site BTW, showing off the DRY principle extremely well 🙂

    1. Hi, yes, you are correct.. session should be closed in getEmployees() method. I am updating the code. Thanks for the feedback and for reporting the issue.

  5. can anyone tell me how to do same above thing in normal jdbc .. rather than in hibernate..
    I want to use jdbc. please provide any link or source.. any help is deeply appreciated.

  6. thanks, works fine. In MyResource.addEmployee() I had to change the parameter to Employee.

  7. im getting error
    org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
    SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.

  8. YOUR REALLY GREAT UR PROVIDING VERY HUGE SUBJECT

  9. […] and other required classes like hibernate.cfg.xml, SessionUtil and Employee entity class.   Adding HIbernare DAO layer for Jersey service   […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: