This is the first of a series of articles about Persistence with Spring. This article will focus on the configuration and implementation of the persistence layer with Spring 3.1 and Hibernate. For a step by step introduction about setting up the Spring context using Java based configuration and the basic Maven pom for the project, see this.
The Persistence with Spring series:
- Part 2 – Simplifying the Data Access Layer with Spring and Java Generics
- Part 3 – The Persistence Layer with Spring 3.1 and JPA
- Part 4 – The Persistence Layer with Spring Data JPA
- Part 5 – Transaction configuration with JPA and Spring 3.1
No More Spring Templates
Starting Spring 3.0 and Hibernate 3.0.1, managing the Hibernate Session with Springs HibernateTemplate is no longer necessary. It is now possible to make use of contextual sessions – sessions managed directly by Hibernate and kept 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.
Exception Translation without the template
One of the responsibilities of HibernateTemplate is exception translation – translating the low level Hibernate exceptions – which tie the API to Hibernate as the single possible ORM – into higher level, generic Spring exceptions.
Without the template to do that, exception translation can still be enabled by annotating the DAOs with the @Repository annotation. That, coupled with a Spring bean postprocessor will advice all @Repository beans with all the implementations of PersistenceExceptionTranslator found in the Spring context – to provide exception translation without using the template.
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.
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()}.
The Spring Java configuration
The Hibernate SessionFactory is set up in the configuration by creating a Spring factory bean to manage it – the AnnotationSessionFactoryBean; this will enable autodetection of the entity classes by classpath scanning. Note that this requires Hibernate 3.2+ and JDK 1.5+.
The alternative is to manually specify all the annotated entity classes to the session factory bean, by using the setAnnotatedClasses method.