Using Spring with JPA and Hibernate

Spring + Hibernate

  • HibernateTemplate is now obsolete (Spring 3.x +) – create bean for SessionFactory and wire it into Hibernate-based Repository beans
  • Use the Hibernate Session api directly
  • This approach has zero dependency on Spring APIs

How to configure:

Configure beans for your datasource, transaction manager and the SessionFactory:

<jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/myds"/>

<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="jtaTransactionManager" ref="txManager"/> 
    <property name="mappingResources">
    <property name="hibernateProperties">

Configuring with xml files is optional if you’re using JPA annotations for your Entities instead.

Repositories using Hibernate follow same ‘new’ pattern as JDBC Template with Spring 3.x, no longer user the HibernateTemplate, inject a Hibernate SessionFactory and use this to get a Session directly. This approach doesn’t have any Spring code dependencies:

public class ExampleRespositoryImpl implements ExampleRepository
  private SessionFactory sessionFactory;

  public ExampleRespositoryImpl(SessionFactory sessionFactory)

  public Example findExampleById(Long id)
    this.sessionFactory.getCurrentSession().get(Example.class, id);

Spring + JPA

How to configure:

Running in an EE container, configure your datasource, transaction manager and EntityManagerFactoryBean:

<jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/MysqlDS"/>

<bean id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>

<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/persistenceUnit"/>

If you’re running outside of an EE container, instead of looking up your datasource and container provided EntityManagerFactory, define a LocalEntityMangerFactoryBean, referencing your persistence unit name:

<bean id="entityManagerFactory"
    <property name="persistenceUnitName" value="persistenceUnit"/>
    <property name="dataSource" ref="dataSource"/>

Configure your persistence.xml to reference your datasource and JPA provider (which may also be Hibernate):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="" xmlns:xsi="" version="2.0"
<persistence-unit name="persistenceUnit" transaction-type="JTA"><!-- for local testing use: RESOURCE_LOCAL -->
         <!-- KH: look up DataSource from container -->

            <!-- KH: ask JBoss to publish the EntityManager so we can reference it in the Spring config -->
            <property name="" value="persistence/persistenceUnit"/>

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
            <property name="" value="update"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/>


If you’re running outside of an EE container, make the following changes:

  • transaction-type="RESOURCE_LOCAL"
  • remove the <jta-data-source> element

Write Repositories with @Repository and @Transactional, and use the @PuersistenceUnit annotation to inject the EntityManagerFactory

public class ExampleRespositoryImpl implements ExampleRepository
  private EntityManagerFactory emf;

    public void setEntityManagerFactory(EntityManagerFactory emf) {
        this.emf = emf;

    public Collection loadProductsByCategory(String category) {
        EntityManager em = this.emf.createEntityManager();
        try {
             Query query = em.createQuery("from Product as p where p.category = ?1");
             query.setParameter(1, category);
             return query.getResultList();
        finally {
            if (em != null) {

This approach injects the EntityManagerFactory using @PersistenceUnit, from which you can get hold of the EntityManager. The normal approach with JPA would be to inject the EntityManager with @PersistenceContext and use the EntityManager directly.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.