Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 119 ยท Spring Framework

Spring ORM: LocalSessionFactoryBean and HibernateTransactionManager

Read classic Spring and Hibernate wiring - LocalSessionFactoryBean, HibernateTransactionManager, getCurrentSession and HibernateTemplate - and learn how to migrate such code to JPA step by step.

Before Spring Boot and Spring Data JPA, connecting Spring to Hibernate meant a few specific beans: a LocalSessionFactoryBean that builds Hibernate's SessionFactory, a HibernateTransactionManager that opens and commits transactions, and DAOs that used either sessionFactory.getCurrentSession() or a helper called HibernateTemplate. Thousands of production systems still run on this "Spring ORM" style. You will meet it when you maintain older code, and understanding it makes modern Spring Data JPA much less magical, because the new tools do the same jobs.

In this lesson you will read the classic configuration, understand how a transaction manager makes one Session available to every DAO call in a request, see what HibernateTemplate did and why it was retired, and follow a migration path to JPA. Spring and Hibernate can't run on this page, so the real configuration is shown read-only and two runnable plain-Java programs model the mechanisms (a thread-bound session with a transaction manager, and the template callback with exception translation). You should know Hibernate's native API, Spring beans and configuration and Spring JDBC.

Native Hibernate integration in Spring (org.springframework.orm.hibernate5) is legacy. New code should use JPA (EntityManager, JpaTransactionManager) or Spring Data JPA, and newer Spring generations are dropping the native package. Treat this lesson as reading and migration knowledge, and check the documentation of your exact Spring and Hibernate versions before changing a running system.

The pieces of classic Spring + Hibernate

flowchart LR
    DS["DataSource<br/>(connection pool)"] --> SF["LocalSessionFactoryBean<br/>builds SessionFactory"]
    SF --> TM["HibernateTransactionManager"]
    TM -->|"binds a Session<br/>to the thread"| DAO["DAO: getCurrentSession()"]
    SVC["@Transactional service"] --> TM
    SVC --> DAO

The transaction manager opens a Session at the start of a @Transactional method and binds it to the thread. The DAO asks the SessionFactory for "the current session" and receives that same one.

Java configuration

Java
@Configuration
@EnableTransactionManagement
@ComponentScan("com.example.shop")
public class PersistenceConfig {

    @Bean
    public DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/shop");
        ds.setUsername("shop");
        ds.setPassword(System.getenv("DB_PASSWORD"));
        return ds;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
        LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setPackagesToScan("com.example.shop.model");         // finds @Entity classes
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        props.setProperty("hibernate.hbm2ddl.auto", "validate");
        props.setProperty("hibernate.show_sql", "false");
        factory.setHibernateProperties(props);
        return factory;
    }

    @Bean
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        return new HibernateTransactionManager(sessionFactory);
    }
}

LocalSessionFactoryBean is a Spring FactoryBean: Spring does not inject the factory object itself but the SessionFactory it produces. It is created once at startup, is thread-safe and expensive, and lives as long as the application. The same wiring in XML (still found in older projects) looks like this:

XML
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="packagesToScan" value="com.example.shop.model"/>
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
      <prop key="hibernate.hbm2ddl.auto">validate</prop>
    </props>
  </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven/>

The DAO with getCurrentSession

Java
@Repository
public class ProductDao {

    private final SessionFactory sessionFactory;

    public ProductDao(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Product find(long id) {
        return sessionFactory.getCurrentSession().get(Product.class, id);
    }

    public void save(Product product) {
        sessionFactory.getCurrentSession().persist(product);
    }

    public List<Product> findByCategory(String category) {
        return sessionFactory.getCurrentSession()
            .createQuery("from Product p where p.category = :c", Product.class)
            .setParameter("c", category)
            .getResultList();
    }
}

@Service
public class CatalogService {
    private final ProductDao dao;
    public CatalogService(ProductDao dao) { this.dao = dao; }

    @Transactional
    public void rename(long id, String newName) {
        Product p = dao.find(id);
        p.setName(newName);               // dirty checking writes the UPDATE at commit
    }
}

Note what the DAO does not do: it never opens or closes a session and never begins a transaction. getCurrentSession() throws HibernateException: No Session found for current thread if no transaction is active, a classic error that nearly always means a missing @Transactional or a call that bypassed the Spring proxy (a method calling another method of its own class). The @Repository annotation also activates exception translation: Hibernate's exceptions become Spring's DataAccessException hierarchy, the same one used by Spring JDBC.

How the transaction manager shares one Session

The key trick is a thread-bound resource. When a @Transactional method starts, the manager opens a session, begins a database transaction, and stores the session in a thread-local map. getCurrentSession() simply reads from that map. At the end the manager commits (or rolls back on a RuntimeException), closes the session and clears the map. Run the model to see the same idea in about sixty lines, using H2 and JDBC in place of Hibernate.

Java A thread-bound session and a transaction manager, with rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the three outcomes. The first transaction commits two rows. In the second, the first insert succeeds but the second violates the CHECK constraint, so the whole transaction rolls back and the monitor row disappears: the count stays at 2. The last call shows getCurrentSession() failing outside a transaction. Notice that the DAO converts the checked SQLException into an unchecked exception, because the manager (like Spring's) rolls back only on unchecked exceptions by default. The next section shows that translation as a reusable pattern.

HibernateTemplate and exception translation

Before getCurrentSession() became the recommended approach, DAOs used HibernateTemplate, a class in the same family as JdbcTemplate. It took a callback, opened or reused a session, ran the callback, and translated exceptions:

Java
public class LegacyProductDao {
    private final HibernateTemplate template;

    public LegacyProductDao(SessionFactory sessionFactory) {
        this.template = new HibernateTemplate(sessionFactory);
    }

    public Product find(long id) {
        return template.get(Product.class, id);
    }

    public List<Product> findByCategory(String category) {
        return template.execute(session ->
            session.createQuery("from Product p where p.category = :c", Product.class)
                   .setParameter("c", category).getResultList());
    }
}

The template's value was the callback + translation pattern. It was retired because Hibernate's own API became easy to use with getCurrentSession(), and because the template tied DAOs to Spring classes. The following program models the pattern: a callback gets a connection, and the template turns low-level SQLExceptions into an unchecked, meaningful hierarchy.

Java A template with a callback and exception translation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Service code now catches DuplicateKeyException instead of checking vendor error codes, which works the same on MySQL, PostgreSQL and H2. That portability is why the Spring DataAccessException hierarchy is still used in JPA and Spring Data code.

In the first model, SQLException is a checked exception, and Spring's default rule is "roll back on unchecked exceptions and errors only". A @Transactional method that throws a checked exception commits unless you write @Transactional(rollbackFor = Exception.class). Translating to DataAccessException (unchecked) is what makes ORM code roll back by default.

Migrating from native Hibernate to JPA

You do not have to rewrite everything at once. A safe path:

  1. Upgrade versions first. Move Spring and Hibernate to the pair your target version supports, and run the tests.
  2. Replace the factory bean. LocalSessionFactoryBean becomes LocalContainerEntityManagerFactoryBean (with HibernateJpaVendorAdapter), and HibernateTransactionManager becomes JpaTransactionManager. Hibernate still sits underneath.
  3. Switch the DAOs. sessionFactory.getCurrentSession() becomes an injected @PersistenceContext EntityManager. Most calls have direct twins: session.get is em.find, session.persist is em.persist, createQuery stays JPQL, Criteria code moves to the JPA Criteria API.
  4. Replace boilerplate DAOs with repositories. Interfaces extending JpaRepository generate the common queries, see Spring Data JPA.
  5. Move to Boot if you want auto-configuration, see Spring Boot Introduction.
Java
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setPackagesToScan("com.example.shop.model");
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    emf.setJpaProperties(hibernateProperties());
    return emf;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    return new JpaTransactionManager(emf);
}
Java
@Repository
public class ProductDao {
    @PersistenceContext
    private EntityManager em;                         // a shared proxy, bound to the current transaction

    public Product find(long id) { return em.find(Product.class, id); }
    public void save(Product p)  { em.persist(p); }
}

The mapping classes (@Entity, relationships) do not change, and the transaction boundaries (@Transactional) stay where they are, so a service layer written in the classic style usually survives the migration untouched. Relationship and fetching problems you already know from Entity Relationships and Fetching and Performance behave the same.

Common problems in classic wiring

  • No Session found for current thread: the call is outside a transaction, @Transactional is missing, or it is a self-call that bypassed the proxy.
  • LazyInitializationException: a lazy association is touched after the transaction ended (often in the view). Fetch what you need inside the service method, or use a join fetch.
  • Two transaction managers: with both JDBC and Hibernate in one application, name the manager explicitly in @Transactional("transactionManager"), or use HibernateTransactionManager, which also exposes its connection to JdbcTemplate on the same DataSource.
  • Version mismatch: Spring's hibernate5 package needs Hibernate 5.x; it does not work with Hibernate 6. That mismatch is the usual blocker when upgrading.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does LocalSessionFactoryBean provide to the rest of the application?

    It is a FactoryBean, so Spring injects the SessionFactory it creates. The factory is built once at startup and shared by all threads.
  2. 2. How does sessionFactory.getCurrentSession() return the same Session in a service method and in the DAO it calls?

    HibernateTransactionManager opens a session at the start of the transaction and binds it to the thread. getCurrentSession reads that binding, and the manager commits and clears it at the end.
  3. 3. You see "No Session found for current thread". What is the most likely cause?

    With no transaction there is no bound session. Usually the @Transactional annotation is missing or the method was called from inside its own class and the proxy was bypassed.
  4. 4. What is the first sensible step when moving from native Hibernate to JPA in a Spring application?

    Swapping the factory and the transaction manager keeps Hibernate underneath, so the entities and transaction boundaries still work while DAOs move to EntityManager gradually.

Summary

  • Classic Spring ORM builds a SessionFactory with LocalSessionFactoryBean and manages transactions with HibernateTransactionManager.
  • DAOs call getCurrentSession() and never open, commit or close sessions; the transaction manager binds one session to the thread per @Transactional call.
  • @Repository adds exception translation to Spring's unchecked DataAccessException hierarchy, which is also why ORM transactions roll back by default.
  • HibernateTemplate (callback plus translation) is legacy; getCurrentSession() replaced it, and JPA replaced both.
  • Migrate by swapping the factory bean and transaction manager first, then DAOs to EntityManager, then to Spring Data repositories.
  • The mismatch between Spring's native Hibernate package and the Hibernate version is the usual upgrade blocker.

Next: Spring MVC puts a web layer on top of the service and DAO layers you have wired here.