Spring @Transactional Service try catch之后不会回滚

一、前言

在开发过程中遇到,在Service层中使用try catch之后,@Transactional没有生效,发生错误之后,事物并没有回滚,在catch中重新抛出 throw new RuntimeException,也没有用。找了另外的解决方案,结果生效了,这里记录一下。

二、code

在catch中加入下面的代码即可解决问题。

// 引用的包
import org.springframework.transaction.interceptor.TransactionAspectSupport;
// 业务代码
try {
    ...
} catch(Exceptione e) {
    e.printStackTrace();
    // 加入这行代码即可
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
发布了68 篇原创文章 · 获赞 48 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Wjhsmart/article/details/100703354
今日推荐