Home  >  Spring Core

Spring Hibernate Integration Example

By Arvind Rai, February 09, 2013
In this page, we learn how to integrate spring with hibernate. Spring is a J2EE framework and Hibernate is a ORM that is Object Relation Mapping Tool.

Why to Integrate Spring with Hibernate

If we integrate these two, they play a great role to run a large application and make the maintenance very easy. Caching and many other performance tuning is handled automatically by these two tools integration. Database can be changed in future without affecting the application code.

How to Integrate Spring With Hibernate

To integrate spring with hibernate we need to configure our application.xml. We have to configure session factory by the class AnnotationSessionFactoryBean. Define HibernateTemplate passing session factory. For the database transaction define HibernateTransactionManager and with the transaction manager configure AOP. Configure all the DAOs. Now we will let you know step by step.

PageDao.java
package com.concretepage.dao;
public interface PageDao {
	public void persist();
}
 
PageDao.java is an interface to represent our Dao. This is declaring a method persists that will perform a task of saving data in Database. In our example we are using MySQl database.

PageDaoImpl.java
package com.concretepage.dao;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.concretepage.persistence.User;
public class PageDaoImpl implements PageDao {
	private HibernateTemplate hibernateTemplate;

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void persist(){
        User u1= new User(1,"Ankita");
        hibernateTemplate.save(u1);
        
        User u2= new User(2,"Renu");
        hibernateTemplate.save(u2);
    }
}
 
PageDaoImpl.java the implantation class of the interface PageDao.java. persist() method has been define here. We get the instance of HibernateTemplate by spring injection. Inside persist method we are creating two User Object and saving to database using HibernateTemplate.

User.java
package com.concretepage.persistence;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User implements Serializable {
  private static final long serialVersionUID = 1L;
  @Id
  private int id;
  private String name;   
  public User(){	  
  }
  public User(int id,String name){
	  this.id=id;
	  this.name=name;
  }
  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;
  } 
} 
 
User.java is an annotated POJO, that is playing the role of representing User instance. In the User class there is an ID and Name of user. @Id is making it as primary.

application.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="configLocation" ><value>hibernate.cfg.xml</value></property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
	<property name="sessionFactory">
	  <ref bean="sessionFactory" />
	</property>
</bean>
<bean id="pageDao" class="com.concretepage.dao.PageDaoImpl">
    <property name="hibernateTemplate">
	  <ref bean="hibernateTemplate" />
	</property>
</bean>

<aop:config>
	<aop:pointcut id="dbOperation" expression="execution(* com.concretepage.dao.PageDaoImpl.*(..))" />
	<aop:advisor advice-ref="txAdvice" pointcut-ref="dbOperation" />	
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
	<tx:attributes>
		<tx:method name="get*" read-only="true" isolation="READ_COMMITTED"/>
		<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" timeout="-1" />
	</tx:attributes>
</tx:advice>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
   <property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
 
application.xml contains all the declaration of DAOs and other transactional configurations. For injecting HibernateTemplate to DAO classes, a bean of org.springframework.orm.hibernate3.HibernateTemplate has been created. For the data integrity, we have used AOP, that will rollback the entry if any failure in transaction happens. The bean of org.springframework.orm.hibernate3.HibernateTransactionManager is playing the role of transactionManager and org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean is creating sessionFactory. To create sessionFactory, we are injecting hibernate.cfg.xml. sessionFactory is being injected to create transactionManager.

hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.url">
    jdbc:mysql://localhost:3306/hibernate</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="com.concretepage.persistence.User"/>
  </session-factory>
</hibernate-configuration>
 
hibernate.cfg.xml is an XML which consists all the database configuration. Database name, POJO mapping, username, password and other database configurations has been declared in hibernate.cfg.xml. To run the Demo, change the configuration according to requirement.

SpringDemo.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.dao.PageDao;
public class SpringDemo {
    public static void main(String... args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            PageDao pd=(PageDao) context.getBean("pageDao");
            pd.persist();
    } 
}
 
Now finally it is the time to run the demo. Find the class SpringDemo.java. SpringDemo is calling persist method from the PageDao to save the data in databse.

Output
Hibernate: insert into User (name, id) values (?, ?)
Hibernate: insert into User (name, id) values (?, ?)
 
Data in database will look like.
Spring Hibernate Integration Example

Jar dependencies in pom.xml for Spring Hibernate Integration

  <properties>
     <spring.version>3.2.2.RELEASE</spring.version>
  </properties>
   <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
	  <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
	  <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
	  <version>2.1_3</version>
    </dependency>
    <dependency>
	 <groupId>mysql</groupId>
	 <artifactId>mysql-connector-java</artifactId>
	 <version>5.1.17</version>
    </dependency>
    <dependency>
     <groupId>javax.inject</groupId>
     <artifactId>javax.inject</artifactId>
     <version>1</version>
    </dependency>
    <dependency>
	 <groupId>org.aspectj</groupId>
	 <artifactId>aspectjweaver</artifactId>
	 <version>1.5.4</version>
   </dependency>
   <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-agent</artifactId> 
     <version>2.5.6</version> 
    </dependency> 
    <dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-tx</artifactId>
	  <version>${spring.version}</version>
    </dependency>
    <dependency>
	 <groupId>org.springframework</groupId>
     <artifactId>spring-jdbc</artifactId>
     <version>${spring.version}</version>
    </dependency>
    <dependency>
	 <groupId>org.codehaus.fabric3.api</groupId>
	 <artifactId>javax-jta</artifactId>
	 <version>1.1.1</version>
    </dependency>
    <dependency>
	 <groupId>commons-dbcp</groupId>
	 <artifactId>commons-dbcp</artifactId>
	 <version>1.2.2</version>
    </dependency>
    <dependency>
	 <groupId>org.hibernate.javax.persistence</groupId>
	 <artifactId>hibernate-jpa-2.0-api</artifactId>
	 <version>1.0.1.Final</version>
    </dependency>
    <dependency>
	 <groupId>org.hibernate</groupId>
	 <artifactId>hibernate-annotations</artifactId>
	 <version>3.5.6-Final</version>
    </dependency>
    <dependency>
	 <groupId>org.slf4j</groupId>
	 <artifactId>slf4j-api</artifactId>
	 <version>1.7.5</version>
    </dependency>
    <dependency>
	 <groupId>javassist</groupId>
	 <artifactId>javassist</artifactId>
	 <version>3.9.0.GA</version>
    </dependency>
  </dependencies>
 


Download Source Code for Spring Hibernate Integration Example

spring_hibernate_integration_example.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us