如果发现事务未生效,请确认@Transactional标注的方法及其子方法没有try/catch。
对于service中调用自身方法,自身方法声明了Transactional注解却事务未生效 @Servicepublic class MyServiceImpl implements MyService{ public void test(){ doTransaction(); } @Transactional public void doTransaction(){}}外部controller调用 MyServiceImpl.test()方法,其中的doTransaction事务无效;
原因: Spring数据库事务约定的实现原理是AOP,而AOP原理是动态代理,在自调用过程中,是类自身的调用,而不是代理对象的调用,就不会产生AOP.
解决方案: 可以从容器中取出service来实现事务
@Servicepublic class MyServiceImpl implements MyService, ApplicationContextAware{ private ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void test(){ MyService service = applicationContext.getBean(MyService.class); service.doTransaction(); } @Override @Transactional public void doTransaction(){}} @Transactional public void test(){ int res = fruitMapper.add(new Fruit("Apple", 12, Arrays.asList("a", "b", "c"))); //插入,由于事务,执行后数据库中并查看不到 System.out.println(JSON.toJSONString(fruitMapper.selectAll())); // 通过代码查询,可以查询到刚才插入的数据 fruitMapper.add(new Fruit("Apple1", 12, Arrays.asList("a", "b", "c"))); }