Hibernate Transaction Management Using Spring

In Hibernate, communication with the database always occurs through a database transaction.

A Hibernate application can run in :

  • non-managed environment : the developer needs to manage the database transactions himself by manually setting the begin, commit or rollback.
  • managed environment : transaction management is performed by an external container.

In this lesson, we will see how to implement a consistent transaction management in Hibernate using Spring Framework.

In this case, the Spring container will take care of all operations related to the session/transaction handling.

 

1. Technologies used

  • Hibernate 4.3.5.Final
  • Spring 4.0.5.RELEASE
  • MySQL 5.1
  • Maven 3.0.5
  • Eclipse 4.5
  • JDK 1.7

 

2. Database table

We crate a database table CUSTOMER.

 

3. Project structure

HibernateTransactionManagementSpring

 

4. pom.xml

We need to add Hibernate and Spring dependencies.

 

5. Model class

File : src/main/java/com/keylesson/persistence/Customer.java

 

6. application context configuration

We start by defining a JDBC DataSource bean and a Hibernate SessionFactory bean.

Then we add the transaction manager bean: we are going to use a Hibernate LocalSessionFactoryBean, which we will use to obtain Hibernate session instances.

The TransactionManager needs a reference to the SessionFactory which needs a reference to the DataSource

By adding the <tx:annotation-driven ../> element, we enable the  annotation-driven transaction management and indicate which transaction manager to use.

We also need to enable Spring auto component scanning on package com.keylesson.dao

File : src/main/resources/applicationContext-hibernate.xml

 

7. DAO class

We are going to create a customer data access object with two methods: the first for creating new customers and the second for listing existing customers.

We annotate it with @Transactional to instruct the Spring container to provide transactional semantics for the DAO’s methods by using the keyTransactionManager.

We use the @Repository annotation to active the auto wire on this class.

And we need to dependency-inject an instance of the sessionFactory into our DAO class.

CustomerDAO.java

 

8. Test It

We are going to add two records to the customer table and then we get the table content and display it.

 

Output :

 

Download source code