SpringBoot 異常回滾 事務的使用

Springboot中事務的使用:java

一、啓動類加上@EnableTransactionManagement註解,開啓事務支持(其實默認是開啓的)。spring

二、在使用事務的public(只有public支持事務)方法(或者類-至關於該類的全部public方法都使用)加上@Transactional註解。框架

在實際使用中通常是在service中使用@Transactional,那麼對於controller->service流程中:ide

若是controller未開啓事務,service中開始了事務,service成功執行,controller在以後的運行中出現異常(錯誤),不會自動回滾。code

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

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

開啓事務的方法中事務回滾的狀況:io

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

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

③注意:若是在try-catch語句中對可能出現的異常(RuntimeException)進行了處理,沒有再手動throw異常,spring認爲該方法成功執行,不會進行回滾,此時須要調用②中方法進行手動回滾 (java 框架項目案例:www.fhadmin.org)

另外,若是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{
}
相關文章
相關標籤/搜索