In this Spring Hibernate Integration with Example tutorial we will see that how to configure the Hibernate with Spring framework with using one example.
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.
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.
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.
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.javapackage com.dineshonjava.sdnext.dao.util; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * @author Dinesh Rajput * */ public abstract class SuperHibernateDaoSupport extends HibernateDaoSupport { }
EmployeeDaoImpl.javapackage 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
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…