在事务⽅法中调⽤另外⼀个事务⽅法,被调⽤⽅法的事务没起作⽤
在事务⽅法中调⽤另外⼀个事务⽅法,被调⽤⽅法的事务没起作⽤
问题描述:(例)
service层有两个事务⽅法insertUser1、insertUser2,当在insertUser1中调⽤insertUser2是,如果前⾯⽅法异常,后边⽅法不会保存
期望:不管insertUser1是否报错,insertUser2 都要报存数据
@Transactional(propagation = Propagation.REQUIRED)
public void insertUser1(){
User user = new User("niu","男",19,"1000000");
userDao.insertUser(user);
this.insertUser2();
//异常
int a = 10/0;
springboot aop}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertUser2(){
User user = new User("xing","⼥",19,"1111111");
userDao.insertUser(user);
}
产⽣问题的原因是:spring是通过代理代管理事务的,当在第⼀个⽅法insertUser1内直接调⽤insertUser2的时候,insertUser2上的事务是不会起作⽤的(也就是insertUser2是没有开启事务)
解决:
springboot:开始aop事务,在启动类application上添加注解@EnableAspectJAutoProxy(exposeProxy = true)
@SpringBootApplication
@EnableAspectJAutoProxy(exposeProxy = true)
public class TestbootApplication {
public static void main(String[] args) {
SpringApplication.run(TestbootApplication.class, args);
}
}
同时在调⽤insertUser2时不直接调⽤,⽽是通过代理的⽅式调⽤:
将代码修改:
@Transactional(propagation = Propagation.REQUIRED)
public void insertUser1(){
User user = new User("niu","男",19,"1000000");
userDao.insertUser(user);
//this.insertUser2();
((UserService)AopContext.currentProxy()).insertUser2();
//异常
int a = 10/0;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertUser2(){
User user = new User("xing","⼥",19,"1111111");
userDao.insertUser(user);
}
这样在调⽤insertUser2的时候回起⽤事务管理(((UserService)AopContext.currentProxy()).insertUser2();⽅法的时候,会将当前事务挂起,重新开启另⼀个新的事务来执⾏语句)
可以通过以下代码来判断类是否是代理类:
boolean isProxy = AopUtils.isAopProxy((UserService)AopContext.currentProxy()); true:是代理类
false:不是代理类
详细博客:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论