Transaction scenario, exception handling, remember to explicitly roll back the transaction

Ali Baba "Java Development Manual": Transaction scene, was thrown after catch, if you need to roll back, be sure to manually roll back the transaction.

 

The following release discounting methods require you to create notes and then create a discounted deal, overall is a transaction. After the catch Exception caught, if not explicitly rolled back, then the front of the "Create notes" submitted to the db. So, in order to ensure the consistency of the transaction, it is necessary to manually roll back the transaction, and returns the highest single failure.

public class TradeOrderServiceImpl{
    @Autowired
    TradeOrderServiceImpl tradeOrderService;

    @Autowired
    DraftInfoServiceImpl draftInfoService;
    
    /**
     * 发布贴现
     *
     */
    @Transactional
    public ResponseModel publish(String merId, String openBank, BigDecimal amt){
        DraftInfoModel draftInfoModel = new DraftInfoModel();
        draftInfoModel.setMerchantId(merId);
        draftInfoModel.setAmt(amt);
        ... ...
        // 创建票据
        DraftInfoModel res_draftInfoModel = draftInfoService.addDraftInfo(draftInfoModel);
        
        the try { 
            TradeOrderModel tradeOrderModel = new new TradeOrderModel (); 
            tradeOrderModel.setSellerMerchantId (merId); 
            tradeOrderModel.setOpenBank (openBank); // openBank long mySQL cause of abnormality Data truncated for column. 
            tradeOrderModel.setPlatFeeAmt (AMT); 
            tradeOrderModel.setDraftId (res_draftInfoModel.getDraftId ()); 
            ... ... 
            // Create discounted transaction 
            TradeOrderModelRes tradeOrderModelRes = tradeOrderService.publishDraftDiscount (tradeOrderModel); 
        } the catch (Exception E) {
             // manual back roll Affairs
            TransactionAspectSupport.currentTransactionStatus () the setRollbackOnly ();.
             // returns the highest single failure 
            return  new new ResponseModel ( to false , ExceptionUtils.getMessage (E)); 
        } 
        
        // return the highest single complete 
        return  new new ResponseModel ( to true ); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/buguge/p/11304993.html