SpringBoot使用注解實現事務管理


conttoller 

    controller和普通的controller類一樣, 不用改變

   @RequestMapping(value = "/path/{id}", method = RequestMethod.DELETE, produces = "application/json")
    @ResponseBody
    public Result delete(HttpServletRequest request,@PathVariable("id") Long id) {
        Result result = null;
        try {
            result = DeleteService.delete(id);
        } catch (Exception e) {
            result = Result.getFailResult("刪除記錄失敗");//前台用來顯示出錯信息
        }
        return result;
    }

Service

   首先在方法上加上 @Transactional(rollbackFor = Exception.class)  , 然后在該方法后面加上 throws Exception ,

   為了不報錯,我們還須 DeleteService 接口中對應的delete()方法簽名修改為:

 

public void delete(Integer personid) throws Exception;

 

rollbackFor  該屬性用於設置需要進行回滾的異常類數組,當方法中拋出指定異常數組中的異常時,則進行事務回滾。

 

@Service
public class DeleteServiceImp implements DeleteService {
   @Override @Transactional(rollbackFor
= Exception.class)//設置檢查時異常時回滾事務 public Result delete(Long id) throws Exception { Result result = null; int num = myMapper.delete(id); int index = 0; if (0 < num) { index = anotherMapper.deleteById(id); if (0 < index) { result = Result.getSuccessResult("刪除版本記錄成功"); } else { throw new Exception("刪除版本記錄失敗"); //刪除關聯表失敗時,拋出一個異常 用來觸發回滾 } } else { throw new Exception("刪除項目失敗"); //刪除失敗時, 拋出異常 用來觸發回滾 } return result; } }

 最后在程序入口類 Application.java 上加上注解 @EnableTransactionManagement , 開啟事務注解

 

參考:https://blog.csdn.net/yerenyuan_pku/article/details/52885041


免責聲明!

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



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