Suggested Pages

Sunday, June 3, 2012

Spring Transaction Rollback

Spring Framework has the following default configuration about transactions:
  • Marks a transaction for rollback when a Unchecked Exceptions is thrown;
  • Doesn't mark a transaction for rollback when a Checked Exceptions is thrown.

PersistenceDAOException.java
package com.simonefolinojavablog.persistence.dao.exception;

public class PersistenceDAOException extends Exception{

 public PersistenceDAOException() {
  super();
 }
}

Transaction rolls back when Unchecked Exceptions is thrown
 @Transactional(propagation = Propagation.REQUIRED)
 public void save(Contact contact) throws PersistenceDAOException {
  entityManager.persist(contact);
  throw new RuntimeException();
 }

The above transaction rolls back because it throws an unchecked exception.

Transaction commits when Checked Exceptions is thrown
 @Transactional(propagation = Propagation.REQUIRED)
 public void save(Contact contact) throws PersistenceDAOException {
  entityManager.persist(contact);
  throw new PersistenceDAOException();
 }
The above transaction commits because it throws a checked exception.

Transaction rolls back when Checked Exceptions is thrown and rollbackForClassName is used
[
 @Transactional(rollbackForClassName={"PersistenceDAOException"} ,
                       propagation = Propagation.REQUIRED)
 public void save(Contact contact) throws PersistenceDAOException {
  entityManager.persist(contact);
  throw new PersistenceDAOException();

 }
The above transaction rolls back because, i have declared PersistenceDAOException in the attribute rollbackForClassName.
Alternatively we can use the AOP confuguration to achieve the same goal.

 
<aop:aspectj-autoproxy />
    
     
<aop:config>
 <aop:pointcut id="rollbackService" expression="execution(public * save(..))" />
 <aop:advisor pointcut-ref="rollbackService" advice-ref="txAdvice" />
</aop:config>

 
<tx:advice id="txAdvice" transaction-manager="transactionManager">
 <tx:attributes>
  <tx:method name="save" rollback-for="PersistenceDAOException" />
 </tx:attributes>
</tx:advice>

No comments :

Post a Comment

Suggested Pages