首页 > 解决方案 > 如何在“TransactionTemplate”上设置“noRollbackFor”?

问题描述

鉴于我有一个如下所示的 TransactionTemplate 设置(我在现有事务中启动新事务),当子事务中的代码引发特定异常时,如何防止父(@Transactional)事务回滚?本质上,模拟 的noRollbackFor参数@Transactional

@Transactional
public void foo() {
    bar();
}

private void bar() {
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    transactionTemplate.setPropagationBehavior(PROPAGATION_REQUIRES_NEW);

    transactionTemplate.execute(__ -> {
        // ...
    });
}

标签: springspring-boot

解决方案


这对于 TransactionTemplate 是不可能的。
TransactionTemplate 不支持回滚规则。
请参阅:https ://github.com/spring-projects/spring-framework/issues/25086

这是设计使然:TransactionTemplate 不支持自定义回滚规则。从技术上讲,TransactionTemplate 甚至不知道 TransactionAttribute,因为该变体是仅由 TransactionInterceptor 支持的扩展定义(因此也存在于后者的包中)。该模板在普通的 TransactionDefinition 上运行,并对其回调抛出的所有异常使用固定的回滚行为,实际上是 RuntimeExceptions 和 Errors。

或者,您可以直接使用 PlatformTransactionManager:注入它,对其调用 getTransaction,执行一些资源操作,然后在 finally 块中调用提交......并以任何您需要的方式处理潜在的运行时异常,而无需调用回滚。您也可以有选择地处理结果,只要您最终调用提交(或回滚,就此而言)来完成事务。

另一种可以更好地控制回滚和失败的解决方案是使用保存点,请参阅https://dzone.com/articles/transaction-savepoints-in-spring-jdbc


推荐阅读