1. 單層事務處理
@Transactional(rollbackFor = Exception.class) public int method(Object obj) { try { doInsert(obj); return 1; } catch(Exception e) { e.printStackTrace(); // // // 加入下行代碼手動回滾 // @Transactional 為方法加上事務,try catch 捕獲到異常手動回滾事務 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // // } return 0; }
或:
@Transactional(rollbackFor = Exception.class) public int method(Object obj) { try { doInsert(obj); return 1; } catch(Exception e) {
throw new RuntimeException(e.getMessage());
} return 0; }
必須 throw ,事務才能捕獲異常,進行回滾。
2. 多層事務處理
@Transactional(rollbackFor = Exception.class) public int method(Object obj) { try { doInsert(obj); return 1; } catch(Exception e) { e.printStackTrace(); // // // 加入下行代碼手動回滾 // @Transactional 為方法加上事務,try catch 捕獲到異常手動回滾事務 if (TransactionAspectSupport.currentTransactionStatus().isNewTransaction()) { // 第一次開啟事務遇到異常則回滾 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } else { // 嵌套的事務,當前方法被另一個加了 @Transactional 標注的方法調用 // 拋出異常告訴上一個事務,讓上一個事務判斷是否回滾 // 這樣的優點是: 在調用者那邊不用根據當前方法返回值來判斷是否回滾 throw e; } // // } return 0; }