一、基础介绍
在 spring 项目中, @Transactional 注解默认会回滚RuntimeException以及其子类,其它范围之外的异常 Spring 不会进行事务回滚
如果也想要回滚,在方法或者类加上@Transactional(rollbackFor = Exception.class)
二、异常体系介绍
三、使用节奏
1.注意事项
添加此注解需要在public方法中进行
2.没有try catch的情况下
添加@Transactional如果存在异常会直接进行回滚
@Override
@Transactional
public CommonResponse addOrModify(Book book) {
CommonResponse<Entity> response = null;
try {
response = baseMapper.insert(entity);
int i = 1/0;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
return response ;
}
3.有try catch的情况下
分为两种情况
1.没有返回值的情况
@Override
@Transactional
public void addOrModify(EntityDto dto) {
CommonResponse<Entity> response = null;
try {
baseMapper.insert(entity);
baseMapper.insertToother(entity);
}
response = CommonResponseFactory.getInstance().success("成功");
} catch (Exception e) {
throw new RuntimeException("save方法运行时异常");
}
}
2.存在返回值的情况
@Override
@Transactional
public CommonResponse addOrModify(EntityDto dto) {
CommonResponse<Entity> response = null;
try {
baseMapper.insert(entity);
baseMapper.insertToother(entity);
}
response = CommonResponseFactory.getInstance().success("成功");
} catch (Exception e) {
response = CommonResponseFactory.getInstance().error("失败");
ExceptionProcessUtils.wrapperHandlerException(response, e);
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return response;
}