Home » Java » Enterprise Java » Hibernate 4 with Spring

About Eugen Paraschiv

Hibernate 4 with Spring

1. Overview

This article will focus on setting up Hibernate 4 with Spring – we’ll look at how to configure Spring 3 with Hibernate 4 using both Java and XML Configuration. Parts of this process are of course common to the Hibernate 3 article.

2. Maven

To add the Spring Persistence dependencies to the project pom.xml, please see the article focused on the Spring and Maven dependencies.

Continuing with Hibernate 4, the Maven dependencies are simple:


Then, to enable Hibernate to use its proxy model, we need javassist as well:


And since we’re going to use MySQL for this tutorial, we’ll also need:


And finally, we are using a proper connection pool instead of the dev-only Spring implementation – the DriverManagerDataSource. We’re using here the Tomcat JDBC Connection Pool:


3. Java Spring Configuration for Hibernate 4

To use Hibernate 4 in a project, a few things have changed on the configuration side when moving from a Hibernate 3 setup.

The main aspect that is different when upgrading from Hibernate 3 is the way to create the SessionFactory with Hibernate 4.

This is now done by using the LocalSessionFactoryBean from the hibernate4 package – which replaces the older AnnotationSessionFactoryBean from the hibernate3 package. The new FactoryBean has the same responsibility – it bootstraps the SessionFactory from annotation scanning. This is neccessary because, starting with Hibernate 3.6, the old AnnotationConfiguration was merged into Configuration and so the new Hibernate 4 LocalSessionFactoryBean is using this new Configuration mechanism.

It is also worth noting that, in Hibernate 4, the Configuration.buildSessionFactory method and mechanism have also been deprecated in favour of Configuration.buildSessionFactory(ServiceRegistry) – which the Spring LocalSessionFactoryBean is not yet using.

The Spring Java Configuration for Hibernate 4:

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;

@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "org.baeldung.spring.persistence" })
public class PersistenceConfig {

   private Environment env;

   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessionFactory.setPackagesToScan(new String[] { "org.baeldung.spring.persistence.model" });

      return sessionFactory;

   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();

      return dataSource;

   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();

      return txManager;

   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();

   Properties hibernateProperties() {
      return new Properties() {
            setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
            setProperty("hibernate.globally_quoted_identifiers", "true");

4. XML Spring Configuration for Hibernate 4

Simillary, Hibernate 4 can be configured with XML as well:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 

   <context:property-placeholder location="classpath:persistence-mysql.properties" />

   <bean id="sessionFactory" 
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="org.baeldung.spring.persistence.model" />
      <property name="hibernateProperties">
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>

   <bean id="dataSource" 
      <property name="driverClassName" value="${jdbc.driverClassName}" />
      <property name="url" value="${jdbc.url}" />
      <property name="username" value="${jdbc.user}" />
      <property name="password" value="${jdbc.pass}" />

   <bean id="txManager" 
      <property name="sessionFactory" ref="sessionFactory" />

   <bean id="persistenceExceptionTranslationPostProcessor" 


To bootstrap the XML into the Spring Context, we can use a simple Java Configuration file if the application is configured with Java configuration:

@ImportResource({ "classpath:hibernate4Config.xml" })
public class HibernateXmlConfig{

Alternativelly we can simply provide the XML file to the Spring Context, if the overall configuration is purely XML.

For both types of configuration, the JDBC and Hibernate specific properties are stored in a properties file:

# jdbc.X

# hibernate.X

5. Spring, Hibernate and MySQL

The Drivers and Dialects supported by Hibernate have been extensively discussed for Hibernate 3 – and everything still applies for Hibernate 4 as well.

6. Usage

At this point, Hibernate 4 is fully configured with Spring and we can inject the raw Hibernate SessionFactory directly whenever we need to:

public abstract class BarHibernateDAO{

   SessionFactory sessionFactory;


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

An important note here is that this is now the recommended way to use the Hibernate API – the older HibernateTemplate is no longer included in the new org.springframework.orm.hibernate4 package as it shouldn’t be used with Hibernate 4.

7. Conclusion

In this example, we configured Spring with Hiberate 4 – both with Java and XML configuration. 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: Hibernate 4 with Spring from our JCG partner Eugen Paraschiv at the baeldung blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....



  1. How to provide the cache provide for the session factory..??
    i am getting exception on that..
    Please help…

  2. Hi, i have implemented a controller to make rest services but it doesnt recognize them… I create a package controllers at the same level of models. What do i have to put in the configuration?

  3. thank you, I won’t go in to details but this helped me with my hibernate properties and SYSTEM_PROPERTIES_MODE_OVERRIDE that i use with EncryptablePropertyPlaceholderConfigurer

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.