Home » Java » Enterprise Java » Hibernate 3 with Spring

About Eugen Paraschiv

Eugen Paraschiv

Hibernate 3 with Spring

1. Overview

This article will focus on setting up Hibernate 3 with Spring – we’ll look at how to use both XML and Java configuration to set up Spring 3 with Hibernate 3 and MySQL.

2. Java Spring Configuration for Hibernate 3

Setting up Hibernate 3 with Spring and Java config is straightforward:

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.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
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 AnnotationSessionFactoryBean sessionFactory() {
      AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
      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"));

Compared to the XML Configuration – described next – there is a small difference in the way one bean in the configuration access another. In XML there is no difference between pointing to a bean or pointing to a bean factory capable of creating that bean. Since the Java configuration is type-safe – pointing directly to the bean factory is no longer an option – we need to retrieve the bean from the bean factory manually:


3. XML Spring Configuration for Hibernate 3

Similarly, we can set up Hibernate 3 with XML config 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" 


Then, this XML file is bootstrapped into the Spring context using a @Configuration class:

@ImportResource({ "classpath:persistenceConfig.xml" })
public class PersistenceXmlConfig {

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

# jdbc.X
# hibernate.X

4. Spring, Hibernate and MySQL

The example above uses MySQL 5 as the underlying database configured with Hibernate – however, Hibernate supports several underlying SQL Databases.

4.1. The Driver

The Driver class name is configured via the jdbc.driverClassName property provided to the DataSource.

In the example above, it is set to com.mysql.jdbc.Driver from the mysql-connector-java dependency we defined in the pom, at the start of the article.

4.2. The Dialect

The Dialect is configured via the hibernate.dialect property provided to the Hibernate SessionFactory.

In the example above, this is set to org.hibernate.dialect.MySQL5Dialect as we are using MySQL 5 as the underlying Database. There are several other dialects supporting MySQL:

  • org.hibernate.dialect.MySQL5InnoDBDialect – for MySQL 5.x with the InnoDB storage engine
  • org.hibernate.dialect.MySQLDialect – for MySQL prior to 5.x
  • org.hibernate.dialect.MySQLInnoDBDialect – for MySQL prior to 5.x with the InnoDB storage engine
  • org.hibernate.dialect.MySQLMyISAMDialect – for all MySQL versions with the ISAM storage engine

Hibernate supports SQL Dialects for every supported Database.

5. Usage

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

public abstract class FooHibernateDAO{

   SessionFactory sessionFactory;


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

6. Maven

To add the Spring Persistence dependencies to the pom, please see the Spring with Maven example – we’ll need to define both spring-context and spring-orm.

Continuing to Hibernate 3, the Maven dependencies are simple:


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


We’re going to use MySQL as our DB for this tutorial, so we’ll also need:


And finally, we will not be using the Spring datasource implementation – the DriverManagerDataSource; instead we’ll use a production ready connection pool solution – Tomcat JDBC Connection Pool:


7. Conclusion

In this example, we configured Hibernate 3 with Spring – 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 3 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 ....


Receive Java & Developer job alerts in your Area from our partners over at ZipRecruiter


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!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns