SQL Zone is brought to you in partnership with:

ahmad has posted 2 posts at DZone. View Full User Profile

Integrating Hibernate with Spring

07.27.2010
| 67891 views |
  • submit to reddit

In this article, we will look at  how Spring affects the application's data-access layer. Our discussion starts with the Data Access Object (DAO) pattern. This pattern, which is popular in the Java world, allows for a more manageable, more maintainable data-access tier. Then, we'll discuss how Spring affects application DAO classes when integrated with Hibernate.

Spring is a general-purpose framework that plays different roles in many areas of application architecture. One of these areas is persistence. Spring does not provide its own persistence framework. Instead, it provides an abstraction layer over JDBC, and a variety of O/R mapping frameworks, such as iBATIS SQL Maps, Hibernate, JDO, Apache OJB, and Oracle TopLink. This abstraction allows consistent, manageable data-access implementation. 

Spring's abstraction layer abstracts the application from the connection factory, the transaction API, and the exception hierarchies used by the underlying persistence technology. Application code always uses the Spring API to work with connection factories, utilizes Spring strategies for transaction management, and involves Spring's generic exception hierarchy to handle underlying exceptions. Spring sits between the application classes and the O/R mapping tool, undertakes transactions, and manages connection objects. It translates the underlying persistence exceptions thrown by Hibernate to meaningful, unchecked exceptions of type DataAccessException. Moreover, Spring provides IoC and AOP, which can be used in the persistence layer. Spring undertakes Hibernate's transactions and provides a more powerful, comprehensive approach to transaction management.

 

The Data Access Object pattern

Although you can obtain a Session object and connect to Hibernate anywhere in the application, it's recommended that all interactions with Hibernate be done only through distinct classes. Regarding this, there is a JEE design pattern, called the DAO pattern. According to the DAO pattern, all persistent operations should be performed via specific classes, technically called DAO classes. These classes are used exclusively for communicating with the data tier. The purpose of this pattern is to separate persistence-related code from the application's business logic, which makes for more manageable and maintainable code, letting you change the persistence strategy flexibly, without changing the business rules or workflow logic.

The DAO pattern states that we should define a DAO interface corresponding to each DAO class. This DAO interface outlines the structure of a DAO class, defines all of the persistence operations that the business layer needs, and (in Spring-based applications) allows us to apply IoC to decouple the business layer from the DAO class.

 

Service Facade Pattern

In implementation of data access tier, the Service Facade Pattern is always used in addition to the DAO pattern. This pattern indicates using an intermediate object, called service object, between all business tier objects and DAO objects. The service object assembles the DAO methods to be managed as a unit of work. Note that only one service class is created for all DAOs that are implemented in each use case.

The service class uses instances of DAO interfaces to interact with them. These instances are instantiated from the concrete DAO classes by the IoC container at runtime. Therefore, the service object is unaware of the actual DAO implementation details.

Regardless of the persistence strategy your application uses (even if it uses direct JDBC), applying the DAO and Service Facade patterns to decouple application tiers is highly recommended.

 

Data tier implementation with Hibernate

Let's now see how the discussed patterns are applied to the application that directly uses Hibernate. The following code shows a sample DAO interface:

package com.packtpub.springhibernate.ch13;

import java.util.Collection;


public interface StudentDao {
public Student getStudent(long id);

public Collection getAllStudents();

public Collection getGraduatedStudents();

public Collection findStudents(String lastName);

public void saveStudent(Student std);

public void removeStudent(Student std);
}

The following code shows a DAO class that implements this DAO interface:

package com.packtpub.springhibernate.ch13;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.Query;

import java.util.Collection;

public class HibernateStudentDao implements StudentDao {

SessionFactory sessionFactory;

public Student getStudent(long id) {
Student student = null;
Session session = HibernateHelper.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
student = (Student) session.get(Student.class, new Long(id));
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
return student;
}

public Collection getAllStudents(){
Collection allStudents = null;
Session session = HibernateHelper.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery(
"from Student std order by std.lastName, std.firstName");
allStudents = query.list();
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e; } finally {
session.close();
}
return allStudents;
}

public Collection getGraduatedStudents(){
Collection graduatedStudents = null;
Session session = HibernateHelper.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery(
"from Student std where std.status=1");
graduatedStudents = query.list();
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
return graduatedStudents;
}

public Collection findStudents(String lastName) {
Collection students = null;
Session session = HibernateHelper.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery(
"from Student std where std.lastName like ?");
query.setString(1, lastName + "%");
students = query.list();
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
return students;
}

public void saveStudent(Student std) {
Session session = HibernateHelper.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(std);
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
}

public void removeStudent(Student std) {
Session session = HibernateHelper.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(std);
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}

 

As you can see, all implemented methods do routines. All obtain a Session object at first, get a Transaction object, perform a persistence operation, commit the transaction, rollback the transaction if exception occurs, and finally close the Session object. Each method contains much boilerplate code that is very similar to the other methods.

Although applying the DAO pattern to the persistence code leads to more manageable and maintainable code, the DAO classes still include much boilerplate code. Each DAO method must obtain a Session instance, start a transaction, perform the persistence operation, and commit the transaction. Additionally, each DAO method should include its own duplicated exception-handling implementation. These are exactly the problems that motivate us to use Spring with Hibernate.

Template Pattern: To clean the code and provide more manageable code, Spring utilizes a pattern called Template Pattern. By this pattern, a template object wraps all of the boilerplate repetitive code. Then, this object delegates the persistence calls as a part of functionality in the template. In the Hibernate case, HibernateTemplate extracts all of the boilerplate code, such as obtaining a Session, performing transaction, and handing exceptions.

 

Data tier implementation with Spring

With Spring, you do not need to implement code for obtaining Session objects, starting and committing transactions, and handling Hibernate exceptions. Instead, you use a HibernateTemplate instance to delegate persistence calls to Hibernate, without direct interaction with Hibernate.

Here are some benefits of using Spring in the persistence layer, instead of using direct interaction with Hibernate:

  • With Spring, the HibernateTemplate object interacts with Hibernate. This object removes the boilerplate code from DAO implementations.
  • Any invocation of one of HibernateTemplate's methods throws the generic DataAccessException exception instead of HibernateException (a Hibernate-specific exception).
  • Spring lets us demarcate transactions declaratively, instead of implementing duplicated transaction-management code.

The HibernateTemplate class uses a SessionFactory instance internally to obtain Session objects for Hibernate interaction. Interestingly, you can configure the SessionFactory object via the Spring IoC container to be instantiated and injected into DAO objects.

The next sections discuss how HibernateTemplate is used in DAO classes, and how it is configured with SessionFactory in the Spring IoC container. First, let's look at the Spring exception hierarchy.

 

Spring exception translation

Spring provides its own exception hierarchy, which sits on the exception hierarchies of the O/R mapping tools it supports. It catches any database exception or error that might be thrown through JDBC, or the underlying O/R mapping tool, and translates the caught exception to a corresponding exception in its own hierarchy. The Spring exception hierarchy is defined as a subclass of org.springframework.dao.DataAccessException. Spring catches any exception thrown in the underlying persistence technology and wraps it in a DataAccessException instance. The DataAccessException object is an unchecked exception, because it extends RuntimeException and you do not need to catch it if you do not want to.

 

Refactoring DAO classes to use Spring

Spring provides distinct DAO base classes for the different data-access technologies it supports. For instance, Spring provides HibernateDaoSupport for Hibernate, SqlMapClientDaoSupport for iBATIS SQL Maps, and JdoDaoSupport for JDO. These classes wrap the common properties and methods that are required in all DAO implementation subclasses.

When you use Hibernate with Spring, the DAO classes extend the Spring org.springframework.orm.hibernate3.support.HibernateDaoSupport class. This class wraps an instance of org.springframework.orm.hibernate3.HibernateTemplate, which in turn wraps an org.hibernate.SessionFactory instance. As you will soon see in this article, extending the HibernateDaoSupport class lets you configure all DAO implementations consistently as beans inside the Spring IoC container. Their SessionFactory property is configured and set up via the Spring context.

The following code shows a simple DAO interface for a Spring-based DAO implementation:

package com.packtpub.springhibernate.ch13;

import java.util.Collection;

public interface StudentDao {
public Student getStudent(long id);

public Collection getAllStudents();

public Collection getGraduatedStudents();

public Collection findStudents(String lastName);

public void saveStudent(Student std);

public void removeStudent(Student std);
}

 

Here, StudentDao is the DAO interface, with the same structure as the interface shown in the following code.

HibernateException is thrown for any failure when directly interacting with Hibernate. When Spring is used, HibernateException is caught by Spring and translated to DataAccessException for any persistence failure. Both exceptions are unchecked, so you do not need to catch them if you don't want to do.

 

The following code shows the DAO implementation for this DAO interface, which now uses Spring to interact with Hibernate:

package com.packtpub.springhibernate.ch13;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.Collection;

public class HibernateStudentDao extends HibernateDaoSupport implements
StudentDao {

public Student getStudent(long id) {
return (Student) getHibernateTemplate().get(Student.class, new
Long(id));
}

public Collection getAllStudents(){
return getHibernateTemplate().
find("from Student std order by std.lastName, std.firstName");
}

public Collection getGraduatedStudents(){
return getHibernateTemplate().find("from Student std where
std.status=1");
}

public Collection findStudents(String lastName) {
return getHibernateTemplate().
find("from Student std where std.lastName like ?",
lastName + "%");
}

public void saveStudent(Student std) {
getHibernateTemplate().saveOrUpdate(std);
}

public void removeStudent(Student std) {
getHibernateTemplate().delete(std);
}
}

 

As you can see, all of the persistent methods in the DAO class use the getHibernateTemplate() method to access the HibernateTemplate object. As you saw in the previous section, HibernateTemplate is a Spring convenience class that delegates DAO calls to the Hibernate Session API. This class exposes all of Hibernate's Session methods, as well as a variety of other convenient methods that DAO classes may need. Because HibernateTemplate convenient methods are not exposed by the Session interface, you can use find() and findByCriteria() when you want to execute HQL or create a Criteria object. Additionally, it wraps all of the underlying exceptions thrown by the Session method with instances of the unchecked org.springframework.dao.DataAccessException.

For convenience, I recommend using the HibernateDaoSupport class as the base class for all Hibernate DAO implementations, but you can ignore this class and work directly with a HibernateTemplate instance in DAO classes. To do so, define a property of HibernateTemplate in the DAO class, which is initialized and set up via the Spring IoC container.

The following code shows the DAO class, which now uses HibernateTemplate directly. Note that this approach is not recommended because it gets you involved with the HibernateTemplate object in both the DAO class and the DAO configuration in the Spring context:

package com.packtpub.springhibernate.ch13;

import org.springframework.orm.hibernate3.HibernateTemplate;

import java.util.Collection;

public class HibernateStudentDao implements StudentDao {

HibernateTemplate hibernateTemplate;

public Student getStudent(long id) {
return (Student) getHibernateTemplate().get(Student.class,
new Long(id));
}

public Collection getAllStudents(){
return getHibernateTemplate().
find("from Student std order by std.lastName, std.firstName");
}

public Collection getGraduatedStudents(){
return getHibernateTemplate().find("from Student std where
std.status=1");
}

public Collection findStudents(String lastName) {
return getHibernateTemplate().
find("from Student std where std.lastName like "+ lastName
+ "%");
}

public void saveStudent(Student std) {
getHibernateTemplate().saveOrUpdate(std);
}

public void removeStudent(Student std) {
getHibernateTemplate().delete(std);
}

public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}

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

The DAO class now has the setHibernateTemplate() method to allow Spring to inject the configured HibernateTemplate instance into the DAO object.

Moreover, the DAO class can abandon the HibernateTemplate class and use the SessionFactory instance directly to interact with Hibernate. The following code shows HibernateStudentDao, which now works directly with the SessionFactory object:

package com.packtpub.springhibernate.ch13;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

import java.util.Collection;

public class HibernateStudentDao implements StudentDao {

SessionFactory sessionFactory;

public Student getStudent(long id) {
Session session =
SessionFactoryUtils.getSession(this.sessionFactory, true);
try {
return (Student) session.get(Student.class, new Long(id));
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} finally {
SessionFactoryUtils.closeSession(session);
}
}

public Collection getAllStudents(){
Session session =
SessionFactoryUtils.getSession(this.sessionFactory, true);
try {

Query query = session.createQuery(
"from Student std order by std.lastName, std.firstName");
Collection allStudents = query.list();
return allStudents;
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} finally {
SessionFactoryUtils.closeSession(session);
}
}

public Collection getGraduatedStudents(){
Session session =
SessionFactoryUtils.getSession(this.sessionFactory, true);
try {
Query query = session.createQuery("from Student std where
std.status=1");
Collection graduatedStudents = query.list();
return graduatedStudents;
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} finally {
SessionFactoryUtils.closeSession(session);
}
}

public Collection findStudents(String lastName) {
Session session =
SessionFactoryUtils.getSession(this.sessionFactory, true);
try {
Query query = session.createQuery(
"from Student std where std.lastName like ?");
query.setString(1, lastName + "%");
Collection students = query.list();
return students;
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} finally {
SessionFactoryUtils.closeSession(session);
}
}

public void saveStudent(Student std) {
Session session =
SessionFactoryUtils.getSession(this.sessionFactory, true);
try {
session.save(std);
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} finally {
SessionFactoryUtils.closeSession(session);
}
}

public void removeStudent(Student std) {
Session session =
SessionFactoryUtils.getSession(this.sessionFactory, true);
try {
session.delete(std);
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
} finally {
SessionFactoryUtils.closeSession(session);
}
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}

In all of the methods above, the SessionFactoryUtils class is used to obtain a Session object. The provided Session object is then used to perform the persistence operation. SessionFactoryUtils is also used to translate HibernateException to DataAccessException in the catch blocks and close the Session objects in the final blocks. Note that this DAO implementation bypasses the advantages of HibernateDaoSupport and HibernateTemplate. You must manage Hibernate's Session manually (as well as exception translation and transaction management) and implement much boilerplate code.

org.springframework.orm.hibernate3.SessionFactoryUtils is a Spring helper class for obtaining Session, reusing Session within transactions, and translating HibernateException to the generic DataAccessException.

This way is absolutely not the way to work with Session in Spring. Always use the HibernateTemplate class to work with Session objects behind the scenes. However, in cases where you need to work directly with Session objects, you can use an implementation of the org.springframework.orm.hibernate3.HibernateCallback interface as the handler to work with Sessions. The following code snippet shows how this approach is:

public void saveStudent(Student std) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws
HibernateException, SQLException {
return session.saveOrUpdate(std);
}
};
getHibernateTemplate().execute(callback);

}

 

In this code, an implicit implementation of HibernateCallback is created and its only doInHibernate() method is implemented. The doInHibernate() method takes an object of Session and returns the result of persistence operation, null if none. The HibernateCallback object is then passed to the execute() method of HibernateTemplate to be executed. The doInHibernate() method just provides a handler to work directly with Session objects that are obtained and used behind the scenes.

AttachmentSize
springHibernate.jpg15.6 KB
Published at DZone with permission of its author, ahmad seddighi.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Sumit Kishore replied on Tue, 2010/07/27 - 1:25pm

The article is generally useful as a tutorial, but I find some of the stances taken by the author as unnecessarily dogmatic, namely that the Service Facade Pattern is "always used" and "only one service class is created for all DAOs".

David Karr replied on Thu, 2010/07/29 - 3:16pm

It's unfortunate that you're not even mentioning JPA. Hibernate is one of several JPA providers. Spring provides a "JPADaoSupport" class, in addition to the other "DaoSupport" variations.

Markus Krüger replied on Mon, 2010/08/02 - 4:19am

As of Spring 3, the use of HibernateTemplate (and its JPA equivalent, JpaTemplate) is no longer recommended. Quoting Chapter 13, Object Relational Mapping (ORM) Data Access of the Spring Framework 3.0 Reference Documentation:
The recommended integration style is to code DAOs against plain Hibernate, JPA, and JDO APIs. The older style of using Spring's DAO templates is no longer recommended; however, coverage of this style can be found in the Section A.1, “Classic ORM usage” in the appendices.

Oliver Gierke replied on Thu, 2010/08/12 - 4:15pm

Good writeup! Although all the stuff you presented is perfectly fine, the tutorial shows you actually don't need to write at all, assuming you're using JPA instead. Admitted, JPA of course does not relieve you from writing that code but so does a project call Hades. This essentially gives you CRUD operations for entities for free plus the feature to simply declare query methods in an interface and get them executed without providing an implementation. For more details checkout our quickstart. Ollie Hades project lead

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.