spring事务
spring 逻辑处理发生异常时需要回滚,使用的是@Transactional注解,其中RollbackFor指定了在哪些异常下面发生回滚,比如以下代码(UserServiceImpl),一个例子
@Transactional(rollbackFor = Exception.class)
public void testTransactional(int userId, String password){
User user = userDao.get(userId);
user.setPassword(password);
userDao.update(user);
// throw new RuntimeException(); 正确回滚
// IOException不能正确回滚,即使rollbackFor设置IOException
/**
try{
throw new IOException();
} catch (IOException e) {
e.printStackTrace();
}
**/
// throw new NullPointerException(); 正确回滚
// throw new CommonException(message); 自定义异常继承RuntimeException,正确回滚
}
public class CommonException extends RuntimeException{
public CommonException(String message){
super(message);
}
}
下图是常见Exception的继承关系,结论就是
- RuntimeException以及其子类都可以回滚
- IOException不能回滚
-
其中SQLSyntaxErrorException也可以正确回滚
但是如果想要程序正确运行,最好还是指定到具体的需要回滚的异常
image.png
网友评论