SpringBoot事務使用和回滾


Springboot中事務的使用:

1、啟動類加上@EnableTransactionManagement注解,開啟事務支持(其實默認是開啟的)。

2、在使用事務的public(只有public支持事務)方法(或者類-相當於該類的所有public方法都使用)加上@Transactional注解。

在實際使用中一般是在service中使用@Transactional,那么對於controller->service流程中:

如果controller未開啟事務,service中開始了事務,service成功執行,controller在之后的運行中出現異常(錯誤),不會自動回滾。

也就是說,只有在開啟事務的方法中出現異常(默認只有非檢測性異常才生效-RuntimeException )(錯誤-Error)才會自動回滾。

 如果想要對拋出的任何異常都進行自動回滾(而不是只針對RuntimeException),只需要在使用@Transactional(rollbackFor = Exception.class)即可。

開啟事務的方法中事務回滾的情況:

①未發現的異常,程序運行過程中自動拋出RuntimeException或者其子類,程序終止,自動回滾。

②使用TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();進行手動回滾。

③注意:如果在try-catch語句中對可能出現的異常(RuntimeException)進行了處理,沒有再手動throw異常,spring認為該方法成功執行,不會進行回滾,此時需要調用②中方法進行手動回滾,如下圖:

另外,如果try-catch語句在finally中進行了return操作,那么catch中手動拋出的異常也會被覆蓋,同樣不會自動回滾。

//不會自動回滾
try{
    throw new RuntimeException();
}catch(RuntimeException e){
    e.printStackTrace();
}finally{
}
//會自動回滾
try{
    throw new RuntimeException();
}catch(RuntimeException e){
    e.printStackTrace();
    throw new RuntimeException();
}finally{
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM