注:本文轉(zhuǎn)載自CSDN論壇。
[原貼地址]{https://blog.csdn.net/weixin_42286635/article/details/103525851}
作者:@問啥啥不會
事務(wù)回滾
在開發(fā)過程中,經(jīng)常會出現(xiàn)一個接口多表插入的情況,當(dāng)其中一張表插入失敗時就需要進(jìn)行事務(wù)回滾了,SpringBoot為我們提供了@Transactional注解來進(jìn)行事務(wù)回滾
要點(diǎn)
1.需要將使用事務(wù)注解的方法設(shè)置為public;
2.如果沒有在注解后做異常配置,只會對手動拋出的 throw new RuntimeException() 起作用;
3.若想對其余異常起作用,則需做類似配置 @Transactional(rollbackFor= Exception.class) ;
回滾方式
1. 手動回滾(try/catch)
如果異常被抓起之后,需要回滾只能手動回滾,否則事務(wù)會認(rèn)為異常已經(jīng)被處理,就不在進(jìn)行回滾
在使用注解后,在需要執(zhí)行事務(wù)回滾的地方,很多時候往往拋出異常進(jìn)行回滾后無法return或者做一些其余的邏輯,那么這種情況使用手動事務(wù)回滾是非常不錯的。
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
@Transactional(rollbackFor=Exception.class)
public Integer test(){
try {
throw new Exception();
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return 0;
}
}
2.自動回滾(直接拋出,不try/catch)
@Transactional(rollbackFor=Exception.class)
public Integer test(){
int i=1/0;//拋出異常,回滾
return 0;
}
3.部分回滾
- 使用Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint(); 設(shè)置回滾點(diǎn)。
- 使用TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);回滾到savePoint。
@Override
@Transactional(rollbackFor = Exception.class)
public Object submitOrder (){
success();
//只回滾以下異常,
Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
try {
exception();
} catch (Exception e) {
e.printStackTrace();
//手工回滾異常
TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
return ApiReturnUtil.error();
}
return ApiReturnUtil.success();
}