I usually post about Persistence on Twitter - you can follow me there:

1. Overview

This article will focus on setting up Hibernate 4 with Spring – we’ll look at how to configure Spring 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 the 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 necessary 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 favor of Configuration.buildSessionFactory(ServiceRegistry) – which the Spring LocalSessionFactoryBean is not yet using.

The Spring Java Configuration for Hibernate 4:

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

   private Environment env;

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

      return sessionFactory;

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

      return dataSource;

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

      return txManager;

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

   Properties hibernateProperties() {
      return new Properties() {

4. XML Spring Configuration for Hibernate 4

Similarly, 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="transactionManager" 
      <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{

Alternatively, 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 Hibernate 4 – both with Java and XML configuration.

As always, the code presented in this article is available over on Github. This is a Maven based project, so it should be easy to import and run as it is.

I usually post about Persistence on Twitter - you can follow me there:

  • tony

    session is auto Close?

    • The question is far to general to know what you’re really asking. Please consider giving some more detail. An even better alternative is to create an github issue for the tutorial project – and I’ll take a look.

      • MK

        I believe what he is asking for is what happens with sessionFactory object. While you use plain java you usually invoke close() method on factory at the end of apllication or ContextListener.contextDestroyed() in web-app. Do spring hadle closing it internally or still you have to handle it manually?
        Any way if it’s what he’s asking or not could you answer me =)?

        • Hey MK – yes, Spring will take care of closing the session factory. If you look at the LocalSessionFactoryBean, you’ll notice that it is a DisposableBean, and the destroy method closes the factory.

  • JavaProgrammer

    It would be nice if you could have indicated where that Spring xml config file should be placed in the project. For example where it would be located if you would be using Maven project? I have tried to implement your solution but it doesn’t work because when I try to inject entitymanager it doesn’t find the configuration file and thus my entity manager is always null.

    • Hey JavaProgrammer – that kind if details is readily available on github – you will find the link to the project at the end of the article. Cheers,

  • Craig

    Hey, I’m trying to use your example but with a com.microsoft.sqlserver.jdbc.SQLServerDriver but the sessionFactory that I have tried to autowire is null. There are no errors in the logs to explain it. Do you know why this could be?

    • Hey Craig – it can be any number of things – my suggestion is to reproduce it somewhere, such as a sample project on github – and I’d be happy to take a look. Cheers,

  • Gaurav Dighe

    I am trying to use Spring 4 and Hibernate4 along with Spring-Data-JPA-1.5. Is everything the same as far as setting up and running the project or is it different?

    • Hey Gaurav, in order to use Spring Data JPA, you’ll have to set up JPA – so no, this configuration won’t work exactly as is; you can check out my intro to Spring Data JPA for the configuration. Cheers,

  • Jason.H

    tks for ur post ! 😀
    where did u configured the tomcat-dbcp for hibernate ? i can see it no where …

    • Hey Jason – it’s the BasicDataSource used in both configuration – that’s part of the tomcat-dbcp jar. Cheers,

  • Dinesh jakhar

    How to setup multiple data sources with Spring mvc 4 and Hibernate 4? Can You help me …….!!

    • Hey Dinesh,
      As I was saying over email, the idea is to simply define multiple data sources manually, in your configuration, and then make sure the layer that sits on top of that is either able to point to these different datasources, or it’s initialized twice – for each data source. Either way it’s a manual process and the out of the box support will get you there, but you still need to do a lot of work by hand. Hope it helps. Cheers,

  • Mahaboob

    In spring configuration how to configure the Hibernate second level cache..?? 🙁

    • Hey Mahaboob – since this is an intro article to setting up Hibernate in Spring, I didn’t cover the second level cache config. Here are a solid writeup that should help you understand how that works and how to use it. Hope it helps. Cheers,

  • Ajit demo

    hi found following issue please help me regarding this issue

    Error creating bean with name ‘homeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.myhibernate.myhibernateapp.UserDao com.myhibernate.myhibernateapp.HomeController.userDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userDao’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.hibernate.SessionFactory com.myhibernate.myhibernateapp.UserDAOImpl.sessionFactory; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;

    • Well Ajit – it looks like you’re missing a class, so you probably need to work on your dependencies and figure out why it’s missing (have a look at the very last nested exception – that’s going to be your root cause).
      Hope that helps. Cheers,

  • Prateek

    I am getting bean creation exception and the root cause is no such method found. This exception I am getting when I have upgraded spring from 3.1.3 to 4.1.3 and the hibernate-core version is 3.6.10. Please let me know if any suggestions form your end to solve my problem.

    • That’s odd – the project that’s referenced by this article is already using Spring 4.2.x and Hibernate 4.3.x – so I’m not sure what you’re upgrading exactly. However, if you can reproduce the issue on the tutorial code, definitely open an issue on Github and I’ll have a look. Cheers,

  • zuno

    Thank you for your tutorial. I’m getting this error:

    org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

    All my services are annotated with @transactional…

    • Hey Zuno,
      That looks like an interesting problem to figure out.
      Have you tried to run the module associated with the article – is it there that you’re seeing the exception?
      If so – definitely open up an issue on Github and I’ll have a look.
      Otherwise, it’s of course hard to diagnose this without running code, here in the comments.
      Hope that helps. Cheers,

  • mamta

    I have tried similar way to create session factory.
    But when we login into our application by multiple user and and try to execute same db operation.
    then one of the session created for one of the user is getting closed.

    • Grzegorz Piwowarek


      It would have been much easier to go through example if you showed us the whole working project on GitHub(or at least small, isolated part that reproduces the problem)

    • Hey Mamta,
      Yeah, Grzegorz has a good point – the comments aren’t a good way to show a huge code sample like that (I had to edit your comment). Feel free to post the question on StackOverflow and followup with the link here and I’d be happy to have a look.