我有两个数据管理器来管理两个非常不相关的表。我想执行一个使用两个数据管理器更新两个表的操作。但是,如果其中一个事务失败,我希望回滚这两个事务。例如,当第一个事务成功,但第二个事务失败时,就会发生这种情况。我希望回滚这两个事务。
由于遗留的原因,我在我的数据管理器中使用spring hibernateTemplate。
发布于 2020-01-03 00:49:50
这可以在Spring中使用@Transactional注解来处理。有两种处理方式,一种是使用注释的声明性事务处理,另一种是编程式事务处理,您必须为此编写一些代码。
如果您使用的是遗留代码,则可以使用编程式事务,我提供了以下代码片段。
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
updateOperation1();
updateOperation2();
} catch (SomeBusinessExeption ex) {
status.setRollbackOnly();
}
}
});您可以参考下面的Spring文档,了解程序化事务。https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html#transaction-programmatic
关于它的完整例子,你可以参考下面的链接。
https://www.tutorialspoint.com/spring/programmatic_management.htm
https://www.baeldung.com/spring-programmatic-transaction-management
https://stackoverflow.com/questions/59566920
复制相似问题