Transaction management using Spring and Hibernate

Categories: Java; Tagged with: ; @ June 26th, 2012 22:07

Spring doesn’t directly manage transactions, it comes with a selection of transaction  managers, such as: DataSourceTransactionManager, HibernateTransactionManager, JpaTransactionManager etc,.

There are two way to manage transaction in Spring: based on programming or configuration. no matter which way we choose, we always need to define the beans needed:

Declaring transactions

Here we define a transactionManager using hibernateTransactionManager, and a transaction template:

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="globalRollbackOnParticipationFailure" value="false" />
      <property name="sessionFactory"  ref="sessionFactory" />
<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="txTemplate" class="">
    <property name="transactionManager" ref="transactionManager"></property>

‘sessionFactory’ bean configuration:

And now, I’ll show you the the two  transaction management ways:

1. by Programming

	private TransactionTemplate txTemplate;
	 * Insert new user using transactionTemplate.
	 * @param user
	public void insertUserByTxTemplate(final User user) {
		txTemplate.execute(new TransactionCallback() {

			public Void doInTransaction(TransactionStatus txStatus) {
				try {
					Session session = sessionFactory.getCurrentSession();;
					throw new RuntimeException("Exception throwed!");
				} catch (Exception e) {
				return null;

Manage transaction using txTemplate.execute().

2. by Configuration/Declaring

using annotation

	 * Insert new user using transaction manager.
	 * @param user
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=RuntimeException.class)
	public void insertUser(User user) {
		Session session = sessionFactory.getCurrentSession(); // SessionFactoryUtils.openSession(sessionFactory);
		// throw new RuntimeException("RunTimeException for Transaction testing...");

If you are using STS(SpringSource tool suite) you can see there is an indicator:


About transaction rollback

  • by default: if there is a runtime exception (UnChecked exception), will rollback;
  • If rollback failed, check the @Transactional,  and the method:  if you get session by SessionFactoryUtils.openSession(sessionFactory),, rollback will failed – I think only sessionFactory.getCurrentSession() can work.


Spring Transaction – automatic rollback of previous db updates when one db update failes
Spring’s @Transactional does not rollback on checked exceptions
Transaction strategies: Understanding transaction pitfalls


// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.