【发布时间】:2018-12-27 19:26:53
【问题描述】:
我有一个事务方法,我想调用另一个可能引发 RuntimeException 的方法。
问题是当异常被抛出时事务被标记为rollbackOnly。
另一个方法调用本身在 try-catch 块中,但我认为当另一个方法通过抛出异常返回时,事务会被标记。
示例:
MyService.java
@Service
public class MyService {
@Autowired
private MyUtils utils;
@Autowired
private MyCrudRepository repository;
@Transactional
public void publicMethod() {
try {
utils.otherPublicMethod();
} catch (Exception ex) {
ex.printStackTrace();
}
// RollbackException: Transaction marked as rollbackOnly
// Even though I caught the exception from the method call itself
repository.save(new MyEntity());
}
}
MyUtils.java
@Component
public class MyUtils {
// Does not use transactions, repositories
// But I think it inherits the transaction and marks it as rollbackOnly
public void otherPublicMethod() {
// Maybe this is seen as an uncaught exception
throw new RuntimeException();
}
}
编辑:
我不认为这是 Does Specifying @Transactional rollbackFor Also Include RuntimeException 的重复,因为异常最终会被捕获。
问题可能类似,因为它还涉及事务和回滚。
【问题讨论】:
-
Spring 事务不依赖于行流,它依赖于类似的方法,如果您在当前方法中有任何异常,它将回滚
-
try-catch块之外一定有什么事情发生。在最后放置一条日志语句......看看它是否被记录 - 同时你看到回滚。 -
同意,有些东西闻起来不对劲。该代码应该可以按照您的意愿工作。
-
@ChristianMüller 不,
RuntimeException也会被try-catch抓住。 -
@MarkRotteveel 我不认为这是标记问题的重复,请查看我的编辑。
标签: java spring spring-boot spring-transactions