Javascript required
Skip to content Skip to sidebar Skip to footer

How to Integrate Spring and Hibernate Using Hibernatedaosupport

23.1 Overview

We saw how to use Hibernate in standalone Java applications and in web applications in the earlier chapter and in this chapter, we will discuss how to integrate hibernate with Spring Framework. We all know Spring and hibernate both are popular frameworks and so a lot can be achieved using both together.

23.2 Integration Approaches

There are multiple ways we can use to integrate Spring with hibernate. Lets discuss the approaches one by one.

23.2.1 LocalSessionFactoryBean –

As its name suggests, this factory bean is responsible to create the hibernate session factories. This factory bean works for XML based hibernate and is depending on the version of hibernate, we  need to use the LocalSessionFactoryBean.

If we are using hibernate4 then org.springframework.orm.hibernate4.LocalSessionFactoryBean and for hibernate3 use org.springframework.orm.hibernate3.LocalSessionFactoryBean

Important  properties of LocalSessionFactoryBean are –

a) datasource - is used to provide the reference of data source

b) mappingResources- this property is of list type and is used to map the hbm files

c) hibernateProperties -    is used to provide the hibernate properties (that we configure in hibernate.cfg.xml file) as a key value pair.

Sample Example of LocalSessionFactoryBean configuration is

<bean id="hibernate3SessionFactory"         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">          <property name="dataSource" ref="dataSource" />              <property name="mappingResources">             <list>                 <value>entity1.hbm.xml</value>             </list>       </property>       <property name="hibernateProperties">             <props>                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect                </prop>                <prop key="hibernate.show_sql">false</prop>             </props>       </property> </bean>        

 For hibernate 4 we just need to change the class to

org.springframework.orm.hibernate4.LocalSessionFactoryBean

In case you are using Hibernate4 with annotated entity beans then use annotatedClasses property to map annotated classes.

23.2.2 AnnotaionSessionFactoryBean –

This is subclass of LocalSessionFactoryBean class and is used for Annotation based hibernate entities (hibernate version 3).

Important  properties of AnnotationSessionFactoryBean are –

a) datasource - is used to provide the reference of data source

b) annotatedClasses - this property is of list type and is used to map the entity classes

c) hibernateProperties-    is used to provide the hibernate properties (that we configure in hibernate.cfg.xml file) as a key value pair.

Sample configuration of AnnotationSessionFactory  class is

        
<bean id="hibernate3AnnotatedSessionFactory"         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">         <property name="dataSource" ref="dataSource" />         <property name="annotatedClasses">             <list>                 <value>com.entity1</value>             </list>         </property>         <property name="hibernateProperties">             <props>                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect                </prop>                <prop key="hibernate.show_sql">false</prop>             </props>         </property> </bean>

Note- LocalSessionFactoryBean and AnnotationSessionFactoryBean classes are innermost classes and other two approaches are dependent on any one these approaches.

23.2.3 HibernateTemplate –

HibernateTemplate class is similar to JDBC Templates approach of Spring Data Access. Depending on the hibernate version we can use

 for hibernate 3 - org.springframework.orm.hibernate3.HibernateTemplate

     for hibernate 4- org.springframework.orm.hibernate4.HibernateTemplate

Hibernate template class depends on session factory so we need to define a session factory and provide its reference using sessionFactory property.

HibernateTemplate does provides several  convenient method like save, update, saveOrUpdate, persist, delete etc corresponding to Hibernate API and these method handles creation/ closing of session internally.

Sample Configuration of HibernateTemplate class as follows

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">    <property name="sessionFactory" ref="sessionFactory"/> </bean>

23.2.4 HibernateDaoSupport –

HibernateDaoSupport is an abstract class is similar to JDBCDaoSupport  approach of Spring Data Access and is a wrapper on top of Hibernate template. We can directly pass the session factory object or can pass hibernate template class as well in the subclasses of HibernateDoaSupport. Subclasses can call getHibernateTemplate() method to get the hibernate template which will be either explicitly passed hibernate template or the one created based on provided session factory

Sample configuration is  (EntityDao is subclass of HibernateDaoSupport)

<bean id="entityDao"   class="com.hibernate.tutorials.EntityDao">   <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean>

23.3  Create Application

23.3.1 Download Spring Framework and its dependencies -

Create an application as we did in chapter 5 of this tutorial. Since this will be a Spring Application  we would need to download Spring framework libraries from http://repo.spring.io/release/org/springframework/spring/ . Spring Framework has a dependency of commons logging libraries so we need to download commons-logging jar files  from http://commons.apache.org/proper/commons-logging/download_logging.cgi

23.3.2 Add Spring and Hibernate libraries in class path -

Add the below 11 jar files of Spring Framework and its dependencies in lib directory of project

  1. commons-logging-1.2.jar
  2. spring-aop-4.1.1.RELEASE.jar
  3. spring-aspects-4.1.1.RELEASE.jar
  4. spring-beans-4.1.1.RELEASE.jar
  5. spring-context-4.1.1.RELEASE.jar
  6. spring-context-support-4.1.1.RELEASE.jar
  7. spring-core-4.1.1.RELEASE.jar
  8. spring-expression-4.1.1.RELEASE.jar
  9. spring-jdbc-4.1.1.RELEASE.jar
  10. spring-orm-4.1.1.RELEASE.jar
  11. spring-tx-4.1.1.RELEASE.jar

Add below 11 jar files of Hibernate in lib directory of project

  1. antlr-2.7.7.jar
  2. dom4j-1.6.1.jar
  3. hibernate-commons-annotations-4.0.5.Final.jar
  4. hibernate-core-4.3.7.Final.jar
  5. hibernate-jpa-2.1-api-1.0.0.Final.jar
  6. jandex-1.1.0.Final.jar
  7. javassist-3.18.1-GA.jar
  8. jboss-logging-3.1.3.GA.jar
  9. jboss-logging-annotations-1.2.0.Beta1.jar
  10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  11. mysql-connector-java-5.1.18-bin.jar

Once done project structure will look like below

23.3.3 Create book-mapping.hbm.xml file in src directory

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC   "-//Hibernate/Hibernate Mapping DTD//EN"  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">   <hibernate-mapping>    <class name="com.tutorial.hibernate.entity.Book" table="Book">       <meta attribute="class-description">          This class contains the employee detail.        </meta>       <id name="id" type="int" column="id">          <generator class="native"/>       </id>       <property name="isbn" column="isbn" type="string"/>       <property name="name" column="name" type="string"/>        <property name="author" column="author" type="string"/>       <property name="publisher" column="publisher" type="string"/>       <property name="price" column="price" type="int"/>           </class> </hibernate-mapping>

23.3.4 Create a Book Entity (Book.java)

package com.tutorial.hibernate.entity;  public class Book {         private int id;     private String isbn;     private String name;     private String author;     private String publisher;     private int price;     public int getId() {         return id;     }     public void setId(int id) {         this.id = id;     }     public String getIsbn() {         return isbn;     }     public void setIsbn(String isbn) {         this.isbn = isbn;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public String getAuthor() {         return author;     }     public void setAuthor(String author) {         this.author = author;     }     public String getPublisher() {         return publisher;     }     public void setPublisher(String publisher) {         this.publisher = publisher;     }     public int getPrice() {         return price;     }     public void setPrice(int price) {         this.price = price;     }     }

23.3.5 Create  Book Table Script

CREATE TABLE 'book' (   'id' int(11) NOT NULL AUTO_INCREMENT,   'isbn' varchar(255) DEFAULT NULL,   'name' varchar(255) DEFAULT NULL,   'author' varchar(255) DEFAULT NULL,   'publisher' varchar(255) DEFAULT NULL,   'price' int(11) DEFAULT NULL,   PRIMARY KEY ('id'); ) ;

23.4 Examples

Let's create examples to persist the data with above discussed approaches.        

23.4.1 Example 1 -Using LocalSessionFactoryBean

a. Create beans.xml in src directory

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">      <bean id="dataSource"         class="org.springframework.jdbc.datasource.DriverManagerDataSource">         <property name="driverClassName" value="com.mysql.jdbc.Driver" />         <property name="url" value="jdbc:mysql://localhost:3306/tutorial" />         <property name="username" value="root" />         <property name="password" value="password" />     </bean>      <bean id="sessionFactory"         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">         <property name="dataSource" ref="dataSource" />         <property name="mappingResources">             <list>                 <value>                     book-mapping.hbm.xml                 </value>             </list>         </property>         <property name="hibernateProperties">             <props>                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>                  <prop key="hibernate.show_sql">false</prop>             </props>         </property>             </bean>      <bean id="bookDao" class="com.tutorial.hibernate.entity.BookDao">         <property ref="sessionFactory" name="sessionFactory"/>     </bean> </beans>

b. Create BookDao Class

package com.tutorial.hibernate.entity; import java.util.List;  import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction;  public class BookDao {     private SessionFactory sessionFactory;      public void setSessionFactory(SessionFactory sessionFactory) {         this.sessionFactory = sessionFactory;     }      public void save(Book book) {         Session session = this.sessionFactory.openSession();         Transaction tx = session.beginTransaction();         session.persist(book);         tx.commit();         session.close();     }      public List<Book> list() {         Session session = this.sessionFactory.openSession();         List<Book> personList = session.createQuery("from Book").list();         session.close();         return personList;     } }

c. Create Test Program

import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.entity.BookDao;  public class Test {     public static void main(String[] args)      {         ApplicationContext context =                  new ClassPathXmlApplicationContext("beans.xml");         BookDao dao = (BookDao)context.getBean("bookDao");                 Book book = new Book();          book.setAuthor("Dummy Author");         book.setIsbn("A1234");         book.setName("Hibernate Integration with Spring");         book.setPrice(233);         book.setPublisher("Unknown");          dao.save(book);             List<Book> books = dao.list();         for(int i=0;i<books.size();i++)         {             Book b = books.get(i);             System.out.println("Book Name: " + b.getName());             System.out.println("Book Author: "+ b.getAuthor());             System.out.println("Book ISBN: "+ book.getIsbn());             System.out.println("Book Price: "+ book.getIsbn());             System.out.println("Book Publisher:" + book.getPublisher() );         }     } }

d. Console Output

23.4.2 Example 2 -Using HibernateTemplate

a. Create beans.xml in src directory

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">      <bean id="dataSource"         class="org.springframework.jdbc.datasource.DriverManagerDataSource">         <property name="driverClassName" value="com.mysql.jdbc.Driver" />         <property name="url" value="jdbc:mysql://localhost:3306/tutorial" />         <property name="username" value="root" />         <property name="password" value="password" />     </bean>      <bean id="sessionFactory"         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">         <property name="dataSource" ref="dataSource" />         <property name="mappingResources">             <list>                 <value>                     book-mapping.hbm.xml                 </value>             </list>         </property>         <property name="hibernateProperties">             <props>                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>                  <prop key="hibernate.show_sql">false</prop>             </props>         </property>             </bean>      <bean id="bookDao" class="com.tutorial.hibernate.entity.BookDao">         <property ref="hibernateTemplate" name="hibernateTemplate"/>     </bean>     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">         <property name="sessionFactory" ref="sessionFactory"/>     </bean> </beans>

b. Create BookDao

package com.tutorial.hibernate.entity;  import org.springframework.orm.hibernate4.HibernateTemplate;  public class BookDao {     private HibernateTemplate hibernateTemplate;      public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {         this.hibernateTemplate = hibernateTemplate;         this.hibernateTemplate.setCheckWriteOperations(false);     }      public void save(Book book) {         hibernateTemplate.save(book);     } }

c. Create Test Program

import java.util.List;  import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;  import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.entity.BookDao;  public class Test {     public static void main(String[] args)      {         ApplicationContext context =                  new ClassPathXmlApplicationContext("beans.xml");                BookDao dao = (BookDao)context.getBean("bookDao");          Book book = new Book();          book.setAuthor("Dummy Author");         book.setIsbn("A1234");         book.setName("Hibernate Integration with Spring");         book.setPrice(233);         book.setPublisher("Unknown");          dao.save(book);             } }        

23.4.3 Example 3 -Using HibernateDaoSupport

a. Create beans.xml in src directory

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">      <bean id="dataSource"         class="org.springframework.jdbc.datasource.DriverManagerDataSource">         <property name="driverClassName" value="com.mysql.jdbc.Driver" />         <property name="url" value="jdbc:mysql://localhost:3306/tutorial" />         <property name="username" value="root" />         <property name="password" value="password" />     </bean>      <bean id="sessionFactory"         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">         <property name="dataSource" ref="dataSource" />         <property name="mappingResources">             <list>                 <value>                     book-mapping.hbm.xml                 </value>             </list>         </property>         <property name="hibernateProperties">             <props>                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>                  <prop key="hibernate.show_sql">false</prop>             </props>         </property>             </bean>      <bean id="bookDao" class="com.tutorial.hibernate.entity.BookDao">         <property ref="hibernateTemplate" name="hibernateTemplate"/>     </bean>      <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">         <property name="sessionFactory" ref="sessionFactory"/>         <property name="checkWriteOperations" value="false"/>     </bean> </beans>        

b. Create BookDao class

package com.tutorial.hibernate.entity;  import org.springframework.orm.hibernate4.support.HibernateDaoSupport;  public class BookDao extends HibernateDaoSupport{      public void save(Book book) {         getHibernateTemplate().save(book);     } }

c. Create Test Program

import java.util.List;  import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;  import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.entity.BookDao;  public class Test {     public static void main(String[] args)      {         ApplicationContext context =                  new ClassPathXmlApplicationContext("beans.xml");          BookDao dao = (BookDao)context.getBean("bookDao");         Book book = new Book();          book.setAuthor("Dummy Author");         book.setIsbn("A1234");         book.setName("Hibernate Integration with Spring");         book.setPrice(233);         book.setPublisher("Unknown");         dao.save(book);             } }        

How to Integrate Spring and Hibernate Using Hibernatedaosupport

Source: https://www.wideskills.com/hibernate/hibernate-integration-spring