如何在 Spring 事务管理中调用自定义回滚方法? [英] How to call a custom rollback method in Spring Transaction Management?
问题描述
环境:Spring 3、自定义事务管理、JDBC 事务
Environment: Spring 3, Custom Transaction Management, JDBC Transactions
我刚刚阅读了有关使用事务模板处理事务管理的 Spring 文档.看起来过于复杂所以我想问:
I just read the Spring docs on using the transaction template to handle transaction management. It seemed overly complex so I want to ask:
我的大部分事务都与 JDBC 相关,这意味着我只是在我的服务上声明了一个 @Transactional
.但是现在我正在对另一个站点进行 REST 服务调用,如果以下任何 JDBC 操作失败,该站点需要回滚,我将在这种情况下提供回滚代码.
Most of my transactions are JDBC related, meaning I just declare an @Transactional
on my service. But now I am making a REST service call to another site which needs to rollback if any of the following JDBC operations fail, I'll provide the rollback code in this case.
随着我的方法的进展,在我的事务中 - 我想保存对 REST 服务调用的引用(需要回滚该操作),并且出现异常时我只是想要一个方法 myCustomRollback()
调用了,它可以访问之前存储的对象.
As I progress in my method, in my transaction - I want to save a reference to the REST service call (needed to roll back that action), and upon exception I just want a method myCustomRollback()
called which can access the previously stored object.
为什么不只在 transactionTemplate 中提供一个映射来存储内容并在 @Transactional
注释上定义自定义回滚方法?
Why not just provide a map in the transactionTemplate for storing stuff and define a custom rollback method on the @Transactional
annotation?
这是我的想法,我没有按照 Spring 的想法来思考这个问题.有人可以帮助我弥合我想要的东西和我如何在 Spring 中最有效地完成它之间的差距吗?我只需要在少数特殊情况下执行此操作.
This is the way I think about it, I'm not following the way Spring thinks about this. Can someone help me bridge the gap between what I want and how I accomplish it most efficiently in Spring? I only need to do this for a few special case operations.
推荐答案
您可以使用 AfterThrowing 建议(当抛出异常时)&在那里调用你的方法 (myCustmRollback()
),你可以使用 TransactionSynchronizationManager
类来获取当前交易 &回滚它...
you can use the AfterThrowing advice (when an exception is thrown) & call your method (myCustmRollback()
) there, you can use TransactionSynchronizationManager
class to get thecurrent transaction & roll it back...
或者..你可以使用AroundAdvice开始&提交/回滚您的事务(这样您就可以通过使用 TransactionSynchronizationManager
类来使用 spring 提供的事务管理器)
alternatively.. you can use the AroundAdvice to begin & commit/rollback your transaction (this way you can use the spring provided transaction manager by using the TransactionSynchronizationManager
class)
这篇关于如何在 Spring 事务管理中调用自定义回滚方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!