spring - 如何在“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(__ -> {
// ...
});
}
解决方案
这对于 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
推荐阅读
- go - 如何在 Golang 中为 cmd 工具编写基准测试?
- python - Ctrl C 不会杀死 Python 中的循环子进程
- php - 如何通过 PHP 代码将文本和图像内容插入谷歌文档
- c - 让用户在 C 中指定一个文件名
- python - 无法在 Tensorflow 的 Keras 中添加两层
- javascript - EventListeners 不适用于 A-Frame 父实体
- docker - 将 JIRA 从本机实例恢复到 docker 容器
- kdb - 如何在kdb中计算年初至今的小计
- javascript - 使用锚标签下载文件时如何获取下载时间?
- c# - 哪个是 ASP.NET Core 上 CloudTableClient 类的最佳 DI 注册范围