The solution for things not rolling back after Spring boot unified exception handling

To deal with the exception of the submitted transaction under springboot, the database does not roll back.

Spring's documentation says that Spring's declarative transaction management defaults to transaction rollback for unchecked exceptions and runtime exceptions, but no rollback for checked exceptions.

What is a checked exception and what is an unchecked exception?
There are two simplest judgment points:
1. Unchecked exceptions inherit from runtimeexception or error, while checked exceptions inherit from exception (of course, runtimeexception itself is also a subclass of exception).

2. Unchecked exceptions do not need to be caught, while checked exceptions must be handled with a try block or handed over to the superior method for processing. In short, code must be written to handle it. So the exception must be caught in the service, and then thrown again, so that the transaction will take effect.

in conclusion:

In the transaction management environment of spring, the use of unckecked exception can greatly simplify the handling of exceptions. It is only necessary to declare the exceptions that may be thrown at the transaction layer (the exception here can be a custom unckecked exception system). It just needs simple throws, no need to capture and process, go directly to the top layer, such as the UI layer, to capture and process exceptions.


Default rules:

1 Let the checked exception also roll back: @Transactional(rollbackFor=Exception.class), generally just add this

2 Make unchecked exceptions not rolled back: @Transactional(notRollbackFor=RunTimeException.class)

3 (query-only) methods that do not require transaction management: @Transactional(propagation=Propagation.NOT_SUPPORTED), or do not add


Note: If the exception is try{}catch{}}, the transaction will not be rolled back. If you want the transaction to be rolled back, you must throw try{}catch{throw Exception}. Because once you try{}catch{} away. The system will think that you have handled the exception manually and will not perform a rollback operation. 


Example:

[java]  view plain copy  
  1. @Override  
  2.   @Transactional(rollbackFor = Exception.class)  
  3.   public Integer submitOrder(FlashbuyOrder flashbuyOrder, List<FlashbuyOrderItem> itemList)  
  4.       throws Exception  
  5.   {  
  6.   
  7.       returnnull;   
  8.   
  9.   }  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325917773&siteId=291194637