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{
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/124071.html
標籤:Java
下一篇:Java基礎-例外
