spring boot 顯示處理事務回滾

hipilee發表於2019-02-22

       顯示處理事務回滾的原因是,我們希望直接在控制層就把異常處理了。同時向前臺反饋錯誤,但是如果在控制層的函式上新增@Transactional註解,必須將異常丟擲,如果必須拋異常

 

//獲取當前登入使用者,指定的MT4賬戶的歷史訂單,分頁獲取
@ResponseBody
@RequestMapping(value = "/deleteMt4", method = {RequestMethod.POST, RequestMethod.GET})
@Transactional
public SysResult deleteMT4(@RequestParam(name = "broker") String broker, @RequestParam(name = "user") String user, @RequestParam(name = "server") String server) throws Exception {
    //獲取當前登入使用者
    Session session = SecurityUtils.getSubject().getSession();
    User userFromSession = session == null ? null : (User) session.getAttribute("user");
    Long userId = userFromSession == null ? null : userFromSession.getUserId();


    SysResult sysResult;
    try {
        try {
            //刪除相應賬戶,此處有點邏輯風險,可能不同的伺服器會有相同的MT4賬號名。
            imt4AccountService.deleteMt4(userId, server, user);
            List<Mt4Account> mt4AccountList = imt4AccountService.list(new QueryWrapper<Mt4Account>().eq("user_id", userId).orderByDesc("is_default"));
            sysResult = SysResult.build(26, "刪除成功", mt4AccountList);
        } finally {

        }
    } catch (RuntimeException r) {
        //程式碼顯示處理回滾 !關鍵
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        sysResult = SysResult.build(260, "刪除失敗", null);
    }
    return sysResult;
}

相關文章