在spring boot 中,使用事務非常簡單,直接在方法上面加入@Transactional 就可以實現,以下是我的做法
@GetMapping("delete")
@ResponseBody
@Transactional
public void delete(@RequestParam("id") int id){
try {
//delete country
this.repository.delete(id);
if(id == 1){
throw Exception("測試事務");
}
//delete city
this.repository.deleteByCountryId(id);
}catch (Exception e){
logger.error("delete false:" + e.getMessage());
return new MessageBean(101,"delete false");
}
}
發現事務不回滾,即 this.repository.delete(id); 成功把數據刪除了。
原因:
默認spring事務只在發生未被捕獲的 RuntimeException 時才回滾。
spring aop 異常捕獲原理:被攔截的方法需顯式拋出異常,並不能經任何處理,這樣aop代理才能捕獲到方法的異常,才能進行回滾,默認情況下aop只捕獲 RuntimeException 的異常,但可以通過配置來捕獲特定的異常並回滾
換句話說在service的方法中不使用try catch 或者在catch中最后加上throw new runtimeexcetpion(),這樣程序異常時才能被aop捕獲進而回滾
解決方案:
方案1.例如service層處理事務,那么service中的方法中不做異常捕獲,或者在catch語句中最后增加throw new RuntimeException()語句,以便讓aop捕獲異常再去回滾,並且在service上層(webservice客戶端,view層action)要繼續捕獲這個異常並處理
方案2.在service層方法的catch語句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();語句,手動回滾,這樣上層就無需去處理異常
1 @GetMapping("delete") 2 @ResponseBody 3 @Transactional 4 public Object delete(@RequestParam("id") int id){ 5 if (id < 1){ 6 return new MessageBean(101,"parameter wrong: id = " + id) ; 7 } 8 try { 9 //delete country 10 this.countryRepository.delete(id); 11 //delete city 12 this.cityRepository.deleteByCountryId(id); 13 return new MessageBean(200,"delete success"); 14 }catch (Exception e){ 15 logger.error("delete false:" + e.getMessage()); 16 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 17 return new MessageBean(101,"delete false"); 18 } 19 }
