0% found this document useful (0 votes)
594 views

Spring Hibernate Integration Using HibernateDaoSupport

The document discusses how to integrate Spring with Hibernate using HibernateDaoSupport. It involves creating a Person entity class and mapping file, a PersonDao class that extends HibernateDaoSupport, a PersonService class, and a DbUtil class to initialize the database. The spring configuration defines beans for the PersonService, PersonDao, HibernateTemplate, data source, and initializes the database.

Uploaded by

Ashwin Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
594 views

Spring Hibernate Integration Using HibernateDaoSupport

The document discusses how to integrate Spring with Hibernate using HibernateDaoSupport. It involves creating a Person entity class and mapping file, a PersonDao class that extends HibernateDaoSupport, a PersonService class, and a DbUtil class to initialize the database. The spring configuration defines beans for the PersonService, PersonDao, HibernateTemplate, data source, and initializes the database.

Uploaded by

Ashwin Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

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. ? Person.java 1 package com.studytrails.tutorials.springhibernatedaosupport; 2 3 4 public class Person { private Integer id; 5 private String name; 6 private String email; 7 8 public Integer getId() { 9 return id; } 10 public void setId(Integer id) { 11 this.id = id; 12 } 13 public String getName() { 14 return name; } 15 public void setName(String name) { 16 this.name = name; 17 } 18 public String getEmail() { 19 return email; } 20 public void setEmail(String email) { 21

this.email = email; 22 } 23 @Override 24 public String toString() { 25 return "Person [id=" + id + ", name=" + name + ", email=" + email + 26"]"; } 27 28 29} 30 31 32

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. ? Person.hbm.xml 1 version="1.0"?> 2 <?xml <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping> <class name="com.studytrails.tutorials.springhibernatedaosupport.Person" 7 table="PERSON"> 8 <id column="ID" name="id" > 9 <generator class="increment"/> </id> 10 <property name="name" column="NAME"/> 11 <property name="email" column="EMAIL"/> 12 </class> 13</hibernate-mapping> 14 15

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 1518 below) using HibernateTemplate.findByCriteria() method. This class demonstrates the usage of Spring Hibernate integration using HibernateDaoSupport. ? PersonDao.java 1 package com.studytrails.tutorials.springhibernatedaosupport; 2 3 import java.util.List; 4 5 import org.hibernate.criterion.DetachedCriteria; 6 import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 7 8 public class PersonDao extends HibernateDaoSupport{ 9 10 public void insert(Person person){ 11 getHibernateTemplate().save(person); 12 } 13 14 public List<Person> selectAll(){ 15 DetachedCriteria criteria = DetachedCriteria.forClass(Person.class); 16 return getHibernateTemplate().findByCriteria(criteria); 17 } 18 19} 20

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). ? PersonService.java package com.studytrails.tutorials.springhibernatedaosupport; 1 2 import java.util.List; 3 4 public class PersonService { 5 6 private PersonDao personDao; 7 public PersonDao getPersonDao() { 8 return personDao; 9 } 10 11 public void setPersonDao(PersonDao personDao) { 12 this.personDao = personDao;

13 14 15 16 17 18 19 20 21} 22 23 24

} public void addPerson(Person person) { getPersonDao().insert(person); } public List<Person> fetchAllPersons() { return getPersonDao().selectAll(); }

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) ? DbUtil.java 1 package com.studytrails.tutorials.springhibernatedaosupport; 2 3 import java.sql.Connection; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 import javax.sql.DataSource; 7 8 public class DbUtil { 9 10 private DataSource dataSource; 11 public DataSource getDataSource() { 12 return dataSource; 13 } 14 15 public void setDataSource(DataSource dataSource) { 16 this.dataSource = dataSource; } 17 18 public void initialize(){ 19 DataSource dataSource = getDataSource(); 20 try { 21 Connection connection = dataSource.getConnection(); 22 Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE PERSON (ID INTEGER, NAME 23 24VARCHAR(50), EMAIL VARCHAR(100))");

25 26 27 28 29 30} 31 32 33

statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } }

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). ? spring-config.xml 1 2 3 4 5 6 7 8 9 1 0 1
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context3.0.xsd">

1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3

<bean id="personService" class="com.studytrails.tutorials.springhibernatedaosupport.PersonSer vice"> <property name="personDao" ref="personDao" /> </bean> <bean id="personDao" class="com.studytrails.tutorials.springhibernatedaosupport.PersonDao "> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>com/studytrails/tutorials/springhibernatedaosupport/P erson.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> <property name="url" value="jdbc:hsqldb:mem://personDb" /> <property name="username" value="sa" /> <property name="password" value="" /> </bean> <bean id="dbUtil" class="com.studytrails.tutorials.springhibernatedaosupport.DbUtil" init-method="initialize"> <property name="dataSource" ref="dataSource" /> </bean> </beans>

4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5

7 5 8 5 9

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). ? TestSpringHibernateDaoSupport.java package com.studytrails.tutorials.springhibernatedaosupport; 1 2 import java.util.List; 3 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 public class TestSpringHibernateDaoSupport { 8 public static void main(String[] args) { 9 System.out.println("************** BEGINNING PROGRAM 10**************"); 11 12 ApplicationContext context = new 13ClassPathXmlApplicationContext("spring-config.xml"); PersonService personService = (PersonService) 14 context.getBean("personService"); 15 16 Person person = new Person(); 17 person.setName("Alba"); 18 person.setEmail("[email protected]"); personService.addPerson(person); 19 System.out.println("Person : " + person + " added successfully"); 20 21 List<Person> persons = personService.fetchAllPersons(); 22 System.out.println("The list of all persons = " + persons); 23 24 System.out.println("************** ENDING PROGRAM

25*****************"); } 26 } 27 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.

You might also like