Integrating Spring Framework with Hibernate ORM Framework: Part 1

0
384
5 min read

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.


Subscribe to the weekly Packt Hub newsletter

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here