简体   繁体   中英

Spring - how to gather informations during rollbacks in declarative transaction management

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM