spring事务失效原因总结

1.调用的方法不是 public 的:

  spring官方文档说明如下:When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

2.自身调用问题:

示例:方法methodB调用方法methodA,方法methodA添加了事务,事务也不会生效。

@Transactional
public void methodA() throws Exception {
throw new RuntimeException();
}

/**
* 这里调用methodA() 的事务将会失效
*/
// @Transactional
// @Transactional(rollbackFor = Exception.class)
public void methodB() throws Exception {
this.methodA();
}

3.捕捉异常没有抛出,事务不生效。


@Transactional
public void methodA() throws Exception {
int id = 1;
try {
Test t = new Test();
t.setId(id);
t.setName("3");
m.updateById(t);
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
// throw new Exception();
// throw new RuntimeException();

} finally {
Test test = m.selectById(id);
log.info("test={}", m.selectById(id));
}

}

4.捕捉异常后, 抛出非RuntimeException异常,事务不生效,需要配置 @Transactional(rollbackFor = Exception.class)即可生效
@Transactional
public void methodA() throws Exception {
int id = 1;
try {
Test t = new Test();
t.setId(id);
t.setName("3");
m.updateById(t);
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
// throw new RuntimeException();

} finally {
Test test = m.selectById(id);
log.info("test={}", m.selectById(id));
}
// throw new RuntimeException();

}


原文地址:https://www.cnblogs.com/liu-xiaolong/p/14081473.html