try catch batch add transaction rollback problems with errors

When we want to add a transaction to a method, we often add @Transactional annotation to the method header

    @ResponseBody
    @RequestMapping(value = "/payment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @Transactional
    public Payment paymentJson(@RequestBody PaymentRequestInfo entity) {
    //method
  }

It is easy to overlook that the @Transactional annotation without any attributes on the method can only trigger the rollback of the transaction when a RuntimeException or Error is thrown. Common non-RuntimeExceptions will not trigger the rollback of the transaction.

If we want to trigger the rollback mechanism when a non-RuntimeException is thrown, we need to add rollbackFor = {Exception.class} attribute to the annotation.

    @ResponseBody
    @RequestMapping(value = "/payment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @Transactional(rollbackFor = { Exception.class })
    public Payment paymentJson(@RequestBody PaymentRequestInfo entity) {
     //method
    }

Of course, the premise of the above transaction rollback is that the @Transactional annotation method does not contain try{...}catch{...} to catch exceptions, so that exceptions during program operation can be thrown smoothly, thereby triggering transaction rollback .

In actual development, we often need to capture exceptions in methods, so as to judge the exceptions and return prompt information for the client. But at this time, because the exception was caught, the rollback of the transaction was not triggered, resulting in the failure of the transaction.

Several solutions are provided below:

1. Use @Transactional annotation to throw RuntimeException recognized by default by @Transactional annotation

The @Transactional annotation is used on the method, and RuntimeException is thrown in the catch statement when an exception is caught.

2. Use @Transactional(rollbackFor = {Exception.class }) to throw the captured non-RuntimeException exception

The method uses @Transactional(rollbackFor = {Exception.class }) annotation to declare the transaction rollback level. When an exception is caught, the caught exception is directly thrown in the catch statement.

3. Manual rollback

The above two methods of throwing exceptions in catch{...} have a shortcoming, that is, there cannot be a return clause in catch{...}, so set manual rollback. When an exception is caught, Manually roll back and return to the foreground prompt message at the same time.

You need to manually roll back the transaction in try catch, use Transactional plus TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 

Or customize the exception class and throw new in try catch

Guess you like

Origin blog.csdn.net/qq_39008613/article/details/105096612