views:

43

answers:

2

Hi,

Could please anybody tell me If it is safe and recommended to catch SQL and other exceptions within @Transactional methods ? When programmatic transaction management is used, I can simply catch the exception and do whatever I want, but I don't know if I don't break the transactional AOP system by catching these exceptions that would otherwise trigger the rollback ... if I do it declarative way.

I suppose there are proxies, that create a logical transaction with separate connection for @Transactional methods in the AOP advices. And they need to catch the exception that "I want to catch" and roll the transaction back.

A: 

What you described is indeed how Spring knows whether or not to initiate a transaction rollback. If you swallow the exception then Spring never has a chance to know that it should rollback the transaction.

matt b
+1  A: 

You can mark the transaction programmatically as rollback-only using this code

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

See Rolling back a declarative transaction in the Spring Reference.

But it's not recommended, because you are coupling your code tightly to the spring framework.


Perhaps, if you do that in more than one place, you should introduce a Helper Method, something like TransactionUtils.rollbackCurrentTransaction(). That way, if you decide to change your transactional approach (or god forbid, move away from spring), you only have to change one method.

seanizer
@seanizer, what I meant is, I need to do stuff when the transaction rolls back...as I would if I could catch the exception where I could for instance log what happened or do something with the bean that was being persisted etc.
lisak
Well then that calls for an AOP advice inside the transaction advice. Read the Spring AOP reference ( http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html ) for info.
seanizer