Tuesday, 16 February 2010

Integrate Hibernate with Spring

I am having a very basic table in MySQL database


DROP TABLE IF EXISTS `test`.`student`;

CREATE TABLE `test`.`student` (

`id` int(10) unsigned NOT NULL default '0',

`name` varchar(255) default NULL,

`age` int(11) default NULL,

PRIMARY KEY (`id`)

);


and here is Student.hbm.xml


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



and here is Student.java bean


import java.io.Serializable;


public class Student implements Serializable {

private String name;

private int age;

private int id;


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public int getAge() {

return age;

}


public void setAge(int age) {

this.age = age;

}


public int getId() {

return id;

}


public void setId(int id) {

this.id = id;

}

}


Now let us get into detail...

The standard way to get a reference to a Hibernate Session object is through an implementation of Hibernate’s SessionFactory interface. Among other things, SessionFactory is responsible for opening, closing, and managing Hibernate Sessions.


The first thing you’ll need to do is to configure a Hibernate session factory bean in Spring.


Spring’s HibernateTemplate provides an abstract layer over a Hibernate Session. HibernateTemplate’s main responsibility is to simplify the work of opening and closing Hibernate Sessions and to convert Hibernate-specific exceptions to one of the Spring ORM exceptions (In the case of Hibernate 2, this means converting a checked HibernateException to an unchecked Spring exception.)


The following XML shows how to configure a HibernateTemplate in Spring:



The sessionFactory property takes a reference to an implementation of org.hibernate.SessionFactory. Here you have a few options, depending on

how you use Hibernate to map your objects to database tables.


-> If you are using Hibernate’s classic XML mapping files, you’ll want to use Spring’s LocalSessionFactoryBean.


LocalSessionFactoryBean is a Spring factory bean that produces a local Hibernate SessionFactory instance that draws its mapping metadata from one or more XML mapping files.


How to configure a LocalSessionFactory-Bean that loads the mapping files for the RoadRantz domain objects:


class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

./student.hbm.xml

hibernate.dialect=org.hibernate.dialect.MySQLDialect


-> For annotation-based Hibernate, Spring’s AnnotationSessionFactoryBean works much like LocalSessionFactoryBean, except that it creates a SessionFactory based on annotations in one or more domain classes.


With the HibernateTemplate bean declared and wired with a session factory, we’re ready to start using it to persist and retrieve objects from the database.


Injected HibernateTemplate into HibernateSampleDao.


public class StudentDAO{

private HibernateTemplate hibernateTemplate;


public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

}


StudentDAO accepts a HibernateTemplate reference via setter injection. So configure it.



saveSample() method that is used to persist a Sample object to the database:


public void saveSample(Student employee){

hibernateTemplate.saveOrUpdate(employee);

}


The saveOrUpdate() method inspects the object to see if its ID field is null. If it is, it must be a new object and thus it is inserted into the database. If it’s not null, it is assumed that it is an existing object and its data is updated.



Now let us look at getEmployee() method that uses HibernateTemplate’s load() method to retrieve a Student by querying by the ID.


public Student getEmployee(int id){

return (Student)hibernateTemplate.load(Student.class, id);

}


So far, the configuration of StudentDAO involves four beans. The datasource is wired into the session factory bean (either LocalSessionFactoryBean or AnnotationSessionFactoryBean). The session factory bean is wired into the HibernateTemplate. Finally, the HibernateTemplate is wired into StudentDAO , where it is used to access the database.


To simplify things slightly, Spring offers HibernateDaoSupport, a convenience DAO support class, that enables you to wire a session factory bean directly into the DAO class. Under the covers, HibernateDaoSupport creates a HibernateTemplate that the DAO can use.


Let’s rework StudentDAO to use HibernateDaoSupport. The first step is to change StudentDAO to extend HibernateDaoSupport:


public class StudentDAO extends HibernateDaoSupport {

}


StudentDAO no longer needs a HibernateTemplate property as it did in previous example. Instead, you can use the getHibernateTemplate() method to get a HibernateTemplate that HibernateDaoSupport creates for you. So, the next step is to change all the data access methods in StudentDAO to use getHibernateTemplate().


For example, here’s the saveSample() method updated for the new HibernateDaoSupport-based StudentDAO :


public void saveSample(Student sample) {

getHibernateTemplate().saveOrUpdate(sample);

}


StudentDAO no longer needs a HibernateTemplate reference, so you can remove it. Instead of a Hibernate-Template, you can directly give reference of a Hibernate SessionFactory so that it can produce a HibernateTemplate internally.




Note :

-> If you’re using Hibernate 2 then you have no other option than to use HibernateTemplate.

No comments:

Post a Comment