Saturday, April 21, 2018

Grails on Groovy > @Transactional does not rollback on checked exceptions

We’re using the Spring Framework in most of our grails applications to manage database transaction.
One of the big advantages is the the declarative transaction handling using the @Transactional attribute.
import org.springframework.transaction.Transactional;
 
@Transactional
public class MyService {
  List exec () {
    
  }
}
That simple annoation on class managed by a Spring ApplicationContext causes all method calls onto that service to be bound to a transaction. The transaction is committed after the method call has left the service again and it’s rollbacked for the case an exception is thrown
But be careful: Only unchecked exceptions (that is, subclasses of java.lang.RuntimeException) are rollbacked by default. For the case, a checked exception is thrown, the transaction will be committed!
And that customization can be done very easily by just adding the parameter rollBackFor to the @Transactional attribute:
import org.springframework.transaction.Transactional;
 
@Transactional(rollbackFor = Exception.class)
public class MyService {
  List exec () {
    
  }
}

No comments:

Post a Comment