Spring Core

Spring Hibernate Integration with Example

In this Spring Hibernate Integration with Example tutorial we will see that how to configure the Hibernate with Spring framework with using one example.

Spring Hibernate Integration

Hibernate is a powerful technology for persisting data in any kind of Application. Spring, on the other hand is a dependency injection framework that supports IOC. The beauty of Spring is that it can integrates well with most of the prevailing popular technologies.

If you are new to Spring and Hibernate frameworks, please read the introduction articles on Spring and Hibernate before start reading this article. DineshonJava has explained in Introduction to Spring Framework. This article will help you to understand the fundamentals of the Spring framework. In another article Introduction to Hibernate published on 27/03/2012 by DineshonJava explains what is ORM framework and how to start writing the simple hibernate application.

Spring and Hibernate:

As a pre-requisite, let us understand the need for such integration before we actually get into the integration between these two technologies. It is well known that Hibernate is a powerful ORM tool that lies between Application and Database. It enables Application to access data from any database in a platform-independent manner. There is no need for the Application to depend on the low-level JDBC details like managing connection, dealing with statements and result sets. All the necessary details for accessing a particular data source is easily configurable in Xml files. Another good thing is that Hibernate can be coupled well with both J2SE and J2EE Applications.

One of the problem with using Hibernate is that the client Application that accesses the database using Hibernate Framework has to depend on the Hibernate APIs like Configuration, SessionFactory and Session. These objects will continue to get scattered across the code throughout the Application. Moreover, the Application code has to manually maintain and manage these objects. In the case of Spring, the business objects can be highly configurable with the help of IOC Container. In simple words, the state of an object can be externalized from the Application code. It means that now it is possible to use the Hibernate objects as Spring Beans and they can enjoy all the facilities that Spring provides.

Integration Spring and Hibernate

We can simply integrate Hibernate configuration with the Spring than struts 2 , In hibernate framework file hibernate.cfg.xml using for the hibernate configuration with the application but in case of Spring there are no need to use this file we can simply configure with in the Spring.xml or applicationContext.xml configuration file. The following sections cover the various steps involved in the Spring-Hiberante integration along with a detailed explanation.

Using Hibernate Mapping file with Spring

  1. Creating Database and Table(Employee Table)
  2. Creating Employee Class(Employee.java)
  3. Creating the Hibernate Mapping file for Employee table(Employee.hbm.xml)
  4. Creating the Spring Configuration File (spring.xml)
  5. Creating the DAO class (EmployeeDao.java)
  6. Creating Application Class for using this

We can also use the Annotation for using this example with following steps.

  1. Creating Database and Table(Employee Table)
  2. Creating Employee Class with using @Entity annotation(Employee.java)
  3. Creating the Spring Configuration File (spring.xml) but creating bean with using annotation
  4. Creating the DAO class (EmployeeDao.java)
  5. Creating Application Class for using this

Now first we see that example using annotation.

Step 1. Creating Database and Table(Employee Table)

CREATE TABLE Employee(
   EMPID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   SALARY BIGINT NOT NULL,
   PRIMARY KEY (ID)
);


Step 2: Creating Employee Class

Employee.java

package com.dineshonjava.sdnext.domain;

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

/**
 * @author Dinesh Rajput
 *
 */
@Entity
@Table(name="Employee")
public class Employee {
 @Id
 @Column(name="EMPID")
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int empid;
 
 @Column(name="NAME")
 private String name;
 
 @Column(name="AGE")
 private int age;
 
 @Column(name="SALARY")
 private long salary;
 /**
  * @return the empid
  */
 public int getEmpid() {
  return empid;
 }
 /**
  * @param empid the empid to set
  */
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 /**
  * @return the name
  */
 public String getName() {
  return name;
 }
 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }
 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }
 /**
  * @param age the age to set
  */
 public void setAge(int age) {
  this.age = age;
 }
 /**
  * @return the salary
  */
 public long getSalary() {
  return salary;
 }
 /**
  * @param salary the salary to set
  */
 public void setSalary(long salary) {
  this.salary = salary;
 }
 
 public String toString(){
  return "EMPLOYEE{empid- "+this.empid+" name- "+this.name+
    " age- "+this.age+" salary- "+this.salary+"}";
 }
}


Step 3: Creating the Spring Configuration File 
(spring.xml)

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:>

 Step 4: Creating the DAO class 
(EmployeeDao.java)
package com.dineshonjava.sdnext.dao;

import java.util.List;

import com.dineshonjava.sdnext.domain.Employee;

/**
 * @author Dinesh Rajput
 *
 */
public interface EmployeeDao {
 /** 
  * This is the method to be used to create
  * a record in the Employee table.
  */
 void createEmployee(Employee employee);
 /** 
  * This is the method to be used to list down
  * a record from the Employee table corresponding
  * to a passed Employee id.
  */
 Employee getEmployee(Integer empid);
 /** 
  * This is the method to be used to list down
  * all the records from the Employee table.
  */
 List listEmployees();
 /** 
  * This is the method to be used to delete
  * a record from the Employee table corresponding
  * to a passed Employee id.
  */
 void delete(Employee employee);
 /** 
  * This is the method to be used to update
  * a record into the Employee table.
  */
 void update(Employee employee);
}


SuperHibernateDaoSupport.java

package com.dineshonjava.sdnext.dao.util;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @author Dinesh Rajput
 *
 */
public abstract class SuperHibernateDaoSupport extends HibernateDaoSupport {

}


EmployeeDaoImpl.java

package com.dineshonjava.sdnext.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.dineshonjava.sdnext.dao.EmployeeDao;
import com.dineshonjava.sdnext.dao.util.SuperHibernateDaoSupport;
import com.dineshonjava.sdnext.domain.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class EmployeeDaoImpl extends SuperHibernateDaoSupport implements EmployeeDao {

 @Override
 public void createEmployee(Employee employee) {
  getHibernateTemplate().saveOrUpdate(employee);
 }

 @Override
 public Employee getEmployee(Integer empid) {
  return (Employee) getHibernateTemplate().get(Employee.class, empid);
 }

 @Override
 public List listEmployees() {
  return getHibernateTemplate().find("FROM EMPLOYEE");
 }

 @Override
 public void delete(Employee employee) {
  getHibernateTemplate().delete(employee);
 }

 @Override
 public void update(Employee employee) {
  getHibernateTemplate().saveOrUpdate(employee);
 }
}

Step 5: Creating Application Class for using this

package com.dineshonjava.sdnext.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dineshonjava.sdnext.dao.EmployeeDao;
import com.dineshonjava.sdnext.domain.Employee;

/**
 * @author Dinesh Rajput
 *
 */
public class EmpMainApp {

 /**
  * @param args
  */
 public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao = (EmployeeDao) context.getBean("employeeDaoImpl");
  
  Employee employee = new Employee();
  employee.setName("Dinesh");
  employee.setAge(25);
  employee.setSalary(50000l);
  System.out.println("------Records Creation--------" );
  empDao.createEmployee(employee);
  System.out.println("------Listing Multiple Records--------" );
  List employees = empDao.listEmployees();
  for (Employee emp: employees) {
        System.out.print(emp);
    }
  System.out.println("------find one Records--------" );
  Employee employee = empDao.getEmployee(3);
  System.out.print(employee);
  System.out.println("------Delete one Records--------" );
  empDao.delete(employee);
 }
}
Output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
------Records Creation--------
Hibernate: insert into Employee (AGE, NAME, SALARY) values (?, ?, ?)
------Listing Multiple Records--------
Hibernate: select employee0_.EMPID as EMPID0_, employee0_.AGE as AGE0_, employee0_.NAME as NAME0_, employee0_.SALARY as SALARY0_ from Employee employee0_
EMPLOYEE{empid- 1 name- Dinesh age- 25 salary- 50000}EMPLOYEE{empid- 2 name- Anamika age- 20 salary- 30000}EMPLOYEE{empid- 3 name- Nimmo age- 24 salary- 30020}EMPLOYEE{empid- 4 name- Adesh age- 24 salary- 30011}EMPLOYEE{empid- 5 name- Vinesh age- 22 salary- 20011}EMPLOYEE{empid- 6 name- Rajesh age- 25 salary- 50000}EMPLOYEE{empid- 7 name- DAV age- 21 salary- 50000}
------find one Records--------
Hibernate: select employee0_.EMPID as EMPID0_0_, employee0_.AGE as AGE0_0_, employee0_.NAME as NAME0_0_, employee0_.SALARY as SALARY0_0_ from Employee employee0_ where employee0_.EMPID=?
EMPLOYEE{empid- 3 name- Nimmo age- 24 salary- 30020}
------Delete one Records--------
Hibernate: delete from Employee where EMPID=?

Source Code from Git Link

https://github.com/DOJ-SoftwareConsultant/SpringHibernateDemo.git

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago