The persistence layer with Spring 3.1 and Hibernate

1. Overview

This article will show how to implement the DAO with Spring and Hibernate. For the core Hibernate configuration, see the articles about Hibernate 3 and Hibernate 4 with Spring.

2. No More Spring Templates

Starting Spring 3.0 and Hibernate 3.0.1, the Spring HibernateTemplate is no longer necessary to manage the Hibernate Session. It is now possible to make use of contextual sessionssessions managed directly by Hibernate and active throughout the scope of a transaction.

As a consequence, it is now best practice to use the Hibernate API directly instead of the HibernateTemplate, which will effectively decouple the DAO layer implementation from Spring entirely.

2.1. Exception Translation without the HibernateTemplate – alive and well

Exception Translation was one of the responsibilities of HibernateTemplate – translating the low level Hibernate exceptions to higher level, generic Spring exceptions.

Without the template, this mechanism is still enabled and active for all the DAOs annotated with the @Repository annotation. Under the hood, this uses a Spring bean postprocessor that will advice all @Repository beans with all the PersistenceExceptionTranslator found in the Spring context.

One thing to remember is that exception translation is done through proxies; in order for Spring to be able to create proxies around the DAO classes, these must not be declared final.

2.2. Hibernate Session management without the Template

When Hibernate support for contextual sessions came out, the HibernateTemplate essentially became obsolete; in fact, the javadoc of the class has been updated with this advice (bold from the original):

NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate3 style of coding data access objects instead, based on {@link org.hibernate.SessionFactory#getCurrentSession()}.

3. The DAO

We’ll start with the base DAO - an abstract, parametrized DAO which supports the common generic operations and is meant to be extended for each entity:

public abstract class AbstractHibernateDAO< T extends Serializable >{
   private Class< T > clazz;

   @Autowired
   private SessionFactory sessionFactory;

   public void setClazz( final Class< T > clazzToSet ){
      clazz = clazzToSet;
   }

   public T findOne( final long id ){
      return (T) getCurrentSession().get( clazz, id );
   }
   public List< T > findAll(){
      return getCurrentSession()
       .createQuery( "from " + clazz.getName() ).list();
   }

   public void save( final T entity ){
      getCurrentSession().persist( entity );
   }

   public T update( final T entity ){
      return (T) getCurrentSession().merge( entity );
   }

   public void delete( final T entity ){
      getCurrentSession().delete( entity );
   }
   public void deleteById( final long id ){
      final T entity = findOne( id);
      delete( entity );
   }

   protected final Session getCurrentSession(){
      return sessionFactory.getCurrentSession();
   }
}

A few aspects are interesting here – as discussed, the abstract DAO does not extend any Spring template (such as HibernateTemplate). Instead, the Hibernate SessionFactory is injected directly in the DAO, and will have the role of the main Hibernate API, through the contextual Session it exposes:

this.sessionFactory.getCurrentSession();

Also, note that the Class of the entity is passed in the constructor to be used in the generic operations.

Now, let’s look at an example implementation of this DAO, for a Foo entity:

@Repository
public class FooDAO extends AbstractHibernateDAO< Foo > implements IFooDAO{

   public FooDAO(){
      setClazz(Foo.class );
   }
}

4. Conclusion

This article covered the configuration and implementation of the persistence layer with Hibernate and Spring 3.1, using both XML and Java based configuration.

The reasons to stop relying on templates for the DAO layer was discussed, as well as possible pitfalls of configuring Spring to manage transactions and the Hibernate Session. The final result is a lightweight, clean DAO implementation, with almost no compile-time reliance on Spring.

The implementation of this simple project can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
 

Reference: The DAO with Spring 3 and Hibernate from our JCG partner Eugen Paraschiv at the baeldung blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


four × = 16



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.