Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring transaction: rollback on Exception or Throwable

Tags:

I wonder whether it makes sense to use instead of

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) 

to use Throwable

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) 

As I understand catching Error will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?

like image 986
Igor Konoplyanko Avatar asked Jan 17 '14 14:01

Igor Konoplyanko


People also ask

Does transaction rollback on exception?

RollbackException exception is thrown when the transaction has been marked for rollback only or the transaction has been rolled back instead of committed. This is a local exception thrown by methods in the UserTransaction , Transaction , and TransactionManager interfaces.

Does Spring rollback on checked exception?

The Spring documentation says: While the EJB default behavior is for the EJB container to automatically roll back the transaction on a system exception (usually a runtime exception), EJB CMT does not roll back the transaction automatically on an application exception (that is, a checked exception other than java. rmi.

Which attribute of @transactional can be used to rollback the operations when a exception of exception type is raised thrown within the method?

@Transactional is setup to rollback, by default, only when an unchecked exception is thrown.

Which of these by default will cause a rollback of the Spring transaction?

By default, the only exceptions that cause a transaction to roll back are the unchecked exceptions (like RuntimeException ).


1 Answers

As I understand catching Error will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?

You don't need to explicitly specify rollbackFor = Throwable.class, because spring will by default rollback the transaction if an Error occurs.

See 12.5.3 Rolling back a declarative transaction

In its default configuration, the Spring Framework's transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. (Errors will also - by default - result in a rollback). Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.

Or take a look at the DefaultTransactionAttribute

public boolean rollbackOn(Throwable ex) {     return (ex instanceof RuntimeException || ex instanceof Error); } 
like image 172
René Link Avatar answered Sep 30 '22 01:09

René Link