Spring Hibernate Integration Using HibernateDaoSupport

Concept Overview

This tutorial explains how spring can be integrated with Hibernate.

HibernateTemplate – Spring provides a class called org.springframework.orm.hibernate3.HibernateTemplate that helps in accessing the database via hibernate. One of its main features is mapping of hibernate exceptions to DataAccessExceptions. The main method in HibernateTemplate is the execute method that takes in a hibernate callback. HibernateTemplate also takes care of obtaining or releasing sessions and hence the callback function or invoking function does not have to manage sessions. The SessionFactory is injected into HibernateTemplate using a LocalSessionFactoryBean. Spring manages the creation and shutting down of the factory. HibernateTemplate provides methods such as find, saveOrUpdate, persist, delete etc that performs the corresponding function in hibernate but manages sessions and exceptions.

LocalSessionFactoryBean – This is a spring factory bean that creates hibernate sessionfactory. The main purpose of this class is to set up the Hibernate SessionFactory in a spring context. The hibernate configuration properties can be passed within the XML. The configuration properties include the hibernate mapping resources, hibernate properties and a datasource. The SessionFactory can handle both pure hibernate session management with single database or transactions that span multiple databases using JTA .

AnnotaionSessionFactoryBean – This is a subclass of LocalSessionFactoryBean but supports annotation based mappings.

HibernateDaoSupport – This class is a convenience class for hibernate based database access. This is a wrapper over HibernateTemplate. It can be initialized using a SessionFactory. It creates the HibernateTemplate and subclasses can use the getHibernateTemplate() method to obtain the hibernateTemplate and then perform operations on it. The class can also be initialized using a preconfigured HibernateTemplate. Create your own DAO by extending this class, provide a SessionFactory or HibernateTemplate and start performing operations using the getHibernateTemplate() method.

Other Tutorials in this series

Spring Transactions, Spring Programmatic Transactions, Spring Declarative Transactions

Sample Program Overview

The sample program demonstrates Spring and hibernate integration. It uses the HibernateDaoSupport to persist an Object of type Person into the database and also demonstrates querying.

We will create the Person class with members as id,name and email.

We will create the PersonDao class with methods insert and selectAll .

We will create the PersonService class with members as personDao.

We will create the DbUtil class with members as dataSource.

Finally, we will test our setup using TestSpringHibernateDaoSupport class which will load Spring context and get a reference to PersonService class. we will use the personService class to add a person to the database and get a list of all persons from the database.

Required Libraries
  • cglib.jar
  • commons-collections.jar
  • commons-logging.jar
  • dom4j.jar
  • hibernate3.jar
  • hsqldb.jar
  • jta-1.1.jar
  • log4j.jar
  • org.springframework.aop.jar
  • org.springframework.asm.jar
  • org.springframework.beans.jar
  • org.springframework.context.jar
  • org.springframework.context.support.jar
  • org.springframework.core.jar
  • org.springframework.expression.jar
  • org.springframework.jdbc.jar
  • org.springframework.orm.jar
  • org.springframework.transaction.jar



Source Code

Create the Person (see sample code below). This is the entity which is inserted and selected from database using Hibernate.

Create Hibernate’s mapping file called Person.hbm.xml (see sample code below).

Map the Person class with the PERSON table (see line 7 below).

Also map the properties Person class with the corresponding columns in PERSON table (see lines 8-12 below).

This mapping file will be used by Hibernate perform Object-Relational Mapping between Person class and PERSON table.

Create PersonDao class (see sample code below) which represents the
Data Access Object
which will interact with the database.

This class extends from
HibernateDaoSupport
(see line 8 below).

The insert() method inserts a Person object into database (see lines 11-13 below) using
HibernateTemplate.save()
method.

Similarly, a list of all Persons is fetched from database using the
selectAll()
method (see lines 15-18 below) using
HibernateTemplate.findByCriteria()
method.

This class demonstrates the usage of Spring Hibernate integration using
HibernateDaoSupport
.

Create PersonService class (see sample code below), a
Service
class which contains reference to PersonDao (see line 7 below).

Create addPerson() and fetchAllPersons() methods which delegate the call to PersonDao (see lines 17-23 below).

Create the DbUtil (see sample code below). This class is used only to create the necessary PERSON table in the database.

Create members dataSource (see line 11 below)

Create accessor methods for dataSource (see lines 13-19 below).

Create the initialize method and execute the ‘CREATE TABLE’ statement to create the PERSON table (see lines 21-32)

Create the spring-config.xml file (see XML configuration below).

The dependency injection chart for the spring-config is as follows:

In particular, note how hibernate mapping file is declared within Spring (see lines 31-35 below).

Also note how Hibernate specific properties are declared within Spring (see lines 36-41 below).

The database parameters defined for dataSource bean (see lines 45-51 below) correspond to the HyperSQL in-memory database.

We also declare the dbUtil bean which initializes the database by creating the PERSON table with ID, NAME and EMAIL columns (see lines 53-57 below).


Finally, we need a java program to test our setup.This is done by TestSpringHibernateDaoSupport (see source code below).

We need to tell Spring framework to use the ‘spring-config.xml’ to load our beans (see line 13 below).

We get the reference to PersonService class through Spring using the bean name ‘personService’ (see line 14 below).

Create the Person object and set the name and email properties (see lines 16-18 below).

Use the PersonService.addPerson() method to add the Person object (see line 19 below).

Use the PersonService.fetchAllPersons() method to list the Persons added to the database (see line 22 below). We access the list of Persons and print the output to verify that database operations of inserting and selecting using
HibernateDaoSupport
within Spring framework have occured successfully (see line 23 below).


Running Sample Program

This sample program has been packaged as a jar installer which will copy the source code (along with all necessary dependencies) on your machine and automatically run the program for you as shown in the steps below. To run the sample program, you only need Java Runtime Environment (JRE) on your machine and nothing else.

Download And Automatically Run Sample Program
  • Save the springhibernatedaosupport-installer.jar on your machine
  • Execute/Run the jar using Java Runtime Environment


  • (Alternatively you can go the folder containing the springhibernatedaosupport-installer.jar and execute the jar using
    java -jar springhibernatedaosupport-installer.jar
    command)

  • You will see a wizard as shown below
  • Enter the location of the directory where you want the program to install and run (say, C:\Temp)
  • The installer will copy the program on your machine and automatically execute it. The expected output indicating that the program has run successfully on your machine is shown in the image below.
  • Browsing the Program

    This source code for this program is downloaded in the folder specified by you (say, C:\Temp) as an eclipse project called
    springhibernatedaosupport
    . All the required libraries have also been downloaded and placed in the same location. You can open this project from Eclipe IDE and directly browse the source code. See below for details of the project structure.

    One thought on “Spring Hibernate Integration Using HibernateDaoSupport

    • March 8, 2017 at 10:44 am
      Permalink

      where is jar file to download

      Reply

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.