English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Integration with Hibernate

We can simply integrate the hibernate application with the spring application.

In the hibernate framework, we provide all the functional database information in the hibernate.cfg.xml file.

But if we want to integrate the hibernate application with spring, there is no need to create a hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.

The Spring framework has the advantages of Hibernate functionality

The Spring framework provides HibernateTemplate Classes, so you don't need to take many steps, such as creating Configuration, BuildSessionFactory, Session, starting and committing transactions, etc.

Therefore It saves a lot of code.

Understanding issues without using Spring:

The following sleep code allows us to understand it:

    //Create configuration
    Configuration cfg=new Configuration();  
    cfg.configure("hibernate.cfg.xml");  
      
    //Create session factory object
    SessionFactory factory=cfg.buildSessionFactory();  
      
    //Create session object  
    Session session=factory.openSession();  
      
    //Create transaction object  
    Transaction t=session.beginTransaction();  
          
    Employee e1=new Employee(111,"arun",40000);  
    session.persist(e1);//persisting the object  
      
    t.commit();//Transaction commit
    session.close();

As you can see in the unique hibernate code, you must follow many steps.

Solution using the HibernateTemplate class of the Spring Framework:

Now, you don't need to take many steps. You can simply write it like this:

    Employee e1=new Employee(111,"arun",40000);  
    hibernateTemplate.save(e1);

Methods of the HibernateTemplate class

Let's take a look at the list of common methods of the HibernateTemplate class.

MethodDescription
void persist(Object entity)Persist the given object.
Serializable save(Object entity)Retain the given object and return the ID.
void saveOrUpdate(Object entity)Persist or update the given object. If an id is found, it will update the record, otherwise it will save the record.
void update(Object entity)Update the given object.
void delete(Object entity)Delete the given object based on the id.
Object get(Class entityClass, Serializable id)Return a persistent object based on the given id.
Object load(Class entityClass, Serializable id)Return a persistent object based on the given id.
List loadAll(Class entityClass)Return all persistent objects.

Steps

Let's see what are the simple steps for integrating Hibernate and Spring:

Create table in the database. This is optional. Create applicationContext.xml file. It contains information such as DataSource, SessionFactory, etc. Create Employee.java file. This is the persistent class Create employee.hbm.xml file. It is the mapping file. Create EmployeeDao.java file. It is a dao class using HibernateTemplate. Create InsertTest.java file. It will call the methods of the EmployeeDao class.

Example of Hibernate and Spring integration

In this example, we will integrate the Hibernate application with Spring. Let's see the structure of the Spring and Hibernate example. Directory structure.


1create table in the database

In this example, we use Oracle as the database, but you can use any database. Let's create a table in the Oracle database.

CREATE TABLE "EMP558" 
   ( "ID" NUMBER(10,0) NOT null ENABLE, 
  "NAME" VARCHAR2(255 CHAR), 
  "SALARY" float(126), 
   PRIMARY KEY ("ID") ENABLE
   )
/

2employee.java

This is a simple POJO class. Here, it is used as a Hibernate persistent class.

package com.w3codebox;
public class Employee {
private int id;
private String name;
private float salary;
//getters and setters
}

3employee.hbm.xml

This mapping file contains all information of the persistent classes.

<?xml version='1.0' encoding='UTF'-8'?>
!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.w3codebox.Employee" table="emp558>
          <id name="id">
          <generator class="assigned"></generator>
          </id>
          
          <property name="name"></property>
          <property name="salary"></property>
</class>
          
</hibernate-mapping>

4and EmployeeDao.java

This is a class using HibernateTemplate Java class for class method to persistently save Employee class objects.

package com.w3codebox;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
  this.template = template;
}
//Method to save an employee
public void saveEmployee(Employee e) {
  template.save(e);
}
//Method to update an employee
public void updateEmployee(Employee e) {
  template.update(e);
}
//Method to delete an employee
public void deleteEmployee(Employee e) {
  template.delete(e);
}
//The method returns an employee with the given id
public Employee getById(int id) {
  Employee e = (Employee)template.get(Employee.class, id);
  return e;
}
//method to return all employees
public List<Employee> getEmployees()
  List<Employee> list = new ArrayList<Employee>();
  list = template.loadAll(Employee.class);
  return list;
}
}

5, applicationContext.xml

In this file, we have BasicDataSource object provides all the information of the database. This object is used LocalSessionFactoryBean class object, which contains some other information, such as mappingResources and hibernateProperties. LocalSessionFactoryBean The object of the class is used in the HibernateTemplate class. Let's take a look at the code of the applicationContext.xml file.

File: applicationContext.xml

<?xml version="1.0" encoding="UTF-8">
<beans
  xmlns="http://www.springframework.org/schema/beans
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
  xmlns:p="http://www.springframework.org/schema/p
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
    <property name="url" value="jdbc:oracle:thin:@localhost:<1521:xe"></property>
    <property name="username" value="system"></property>
    <property name="password" value="oracle"></property>
  </bean>
  
  <bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    
    <property name="mappingResources">
    <list>
    <value>employee.hbm.xml</value>
    </list>
    </property>
    
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.Oracle<9Dialect</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
        <prop key="hibernate.show_sql">true</prop>
        
      </props>
    </property>
  </bean>
  
  <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="mysessionFactory"></property>
  </bean>
  
  <bean id="d" class="com.w3codebox.EmployeeDao">
  <property name="template" ref="template"></property>
  </bean>
  
  
  </beans>

6、InsertTest.java

This class uses the EmployeeDao object and calls its saveEmployee method by passing an Employee object.

package com.w3codebox;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
  
  Resource r = new ClassPathResource("applicationContext.xml");
  BeanFactory factory = new XmlBeanFactory(r);
  
  EmployeeDao dao = (EmployeeDao)factory.getBean("d");
  
  Employee e = new Employee();
  e.setId(114);
  e.setName("varun");
  e.setSalary(50000);
  
  dao.saveEmployee(e);
  
}
}

Now, if you see the table in the Oracle database, the record has been successfully inserted.

Enable automatic table creation, display SQL queries, etc.

You can enable hibernate properties in the applicationContext.xml file, for example by using hbm2Automatic table creation with ddl.auto and other settings. Let's see the code:

<property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.Oracle<9Dialect</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
        <prop key="hibernate.show_sql">true</prop>
        
      </props>

If you write this code, you do not need to create a table because it will be automatically created.