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.

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.
Spring Hibernate Integration with 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.
Popular Tutorials
  1. Spring Tutorial
  2. Spring MVC Web Tutorial
  3. Spring Boot Tutorial
  4. Spring JDBC Tutorial
  5. Spring AOP Tutorial
  6. Spring Security Tutorial

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.

Spring and Hibernate Example

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:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd 
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  
<context:annotation-config></context:annotation-config>
  
<context:component-scan base-package="com.dineshonjava.sdnext.dao.impl">
</context:component-scan>

<!-- Creating data source -->  
<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
 <property name="url" value="jdbc:mysql://localhost:3306/DAVDB"></property>
 <property name="username" value="root"></property>
 <property name="password" value="root"></property>
 <property name="initialSize" value="2"></property>
 <property name="maxActive" value="5"></property>
</bean>
 
<!-- Creating session factory --> 
<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">
               org.hibernate.dialect.MySQLDialect
        </prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>
 
    <property name="annotatedClasses">
      <list>
 <value>
             com.dineshonjava.sdnext.domain.Employee
         </value>
      </list>
    </property>
</bean>
   
<bean class="com.dineshonjava.sdnext.dao.impl.EmployeeDaoImpl" id="employeeDaoImpl">
    <property name="sessionFactory" ref="sessionFactory">
</property></bean>
</beans>

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




No comments:

Post a Comment