controller層使用@Transactional事務注解


一般情況下,@Transactional要放在service層,並且只需要放到最外層的方法上就可以了。

controller層使用@Transactional注解是無效的。但是可以在controller層方法的catch語句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();語句,手動回滾,這樣上層就無需去處理異常

@RequestMapping(value = "/delrecord", method = {RequestMethod.GET})
    @Transactional(rollbackFor = Exception.class)
    public String delRecord(HttpServletRequest request) {
        try {
        //省略業務代碼……
        } catch (Exception e) {
            log.error("操作異常",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//contoller中增加事務
            return failure("操作失敗!");
        }
    }

 特別注意:如下代碼發現事務不回滾,即 this.repository.delete(id); 成功把數據刪除了。

    @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");
        }
    }

原因:

默認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:在controller層方法的catch語句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();語句,手動回滾,這樣上層就無需去處理異常

      @GetMapping("delete") 
      @ResponseBody 
      @Transactional 
      public Object delete(@RequestParam("id") int id){ 
          if (id < 1){
               return new MessageBean(101,"parameter wrong: id = " + id) ; 
           } 
        try { 
              //delete country
               this.countryRepository.delete(id);
               //delete city
               this.cityRepository.deleteByCountryId(id);
               return new MessageBean(200,"delete success");
           }catch (Exception e){
               logger.error("delete false:" + e.getMessage());
               TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
               return new MessageBean(101,"delete false");
          }
      }

 


免責聲明!

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



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