springboot事务的使用
SpringBoot使用事物的步骤:
- 在启动类添加注解@EnableTransactionManagement
- 在业务层使用注解:@Transactional
注:
①需要添加事务注解的再添加给注解,不需要的就不要添加
②事务注解最好添加在方法上,不要添加在类上
③在实际使用中一般是在service中使用@Transactional,那么对于controller->service流程中:
如果controller未开启事务,service中开始了事务,service成功执行,controller在之后的运行中出 现异常(错误),不会自动回滚。
也就是说,只有在开启事务的方法中出现异常(默认只有非检测性异常才生效-RuntimeException ) (错误-Error)才会自动回滚。
④ 如果想要对抛出的任何异常都进行自动回滚(而不是只针对RuntimeException),只需要在使用@Transactional(rollbackFor = Exception.class)即可。
如果在try-catch语句中对可能出现的异常(RuntimeException)进行了处理,没有再手动throw异常,spring认为该方法成功执行,不会进行回滚
//不会自动回滚
try{
throw new RuntimeException();
}catch(RuntimeException e){
e.printStackTrace();
}finally{
}
//会自动回滚
try{
throw new RuntimeException();
}catch(RuntimeException e){
e.printStackTrace();
throw new RuntimeException();
}finally{
}
参考博客:
https://blog.csdn.net/justry_deng/article/details/80828180
https://www.cnblogs.com/ZTPX/p/10566498.html