1.在一个Service类的某个方法中,直接调用另外一个事务方法
@Service
public class Test {
public void a(){
System.out.println("a方法执行了");
b();
}
@Transactional
public void b(){
System.out.println("b方法执行了");
}
}
原因分析:b方法拥有事务的能力是因为spring aop生成代理了对象,但是这种方法直接调用了this对象的方法,所以b方法不会生成事务
2.没有遵循默认的事务规则,也没有指定异常进行事务回滚
@Transactional
public insertUser(User user) throws Exception{
userMapper.insertUser(user);
insertUserRole(user);
// 模拟抛出SQLException异常
boolean flag = true;
if (flag){
throw new SQLException("发生异常了..");
}
}
原因分析:因为Spring
的默认的事务规则是遇到运行异常(RuntimeException)
和程序错误(Error)
才会回滚。如果想针对检查异常进行事务回滚,可以在@Transactional
注解里使用 rollbackFor
属性明确指定异常。
3.在业务层捕捉异常后 把异常“吃”掉了
@Transactional(rollbackFor = Exception.class)
public int insertUser(User user) throws Exception{
insertUser(user);
insertUserRole(user);
// 模拟抛出SQLException异常
boolean flag = true;
if (flag)
{
try
{
// 谨慎:尽量不要在业务层捕捉异常并处理
throw new Exception("发生异常了..");
}
catch (Exception e)
{
e.printStackTrace();
}
}
return rows;
}
原因分析:在业务层捕捉异常后,发现事务不生效。 这是许多新手都会犯的一个错误,在业务层手工捕捉并处理了异常,你都把异常“吃”掉了,Spring
自然不知道这里有错,更不会主动去回滚数据
4.事务方法的访问权限定义不是public,这样会导致事务失效,spring要求被代理方法必须是public
的
5.事务方法定义成了final
6.以及等等