Analysis on the transaction error report to solve the do not call commit or rollback more than once per transaction error report

Analysis on the error report of do not call commit or rollback more than once per transaction

error log

org.springframework.transaction.IllegalTransactionStateException: Transaction is already completed - do not call commit or rollback more than once per transaction
	at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:804) ~[spring-tx-5.3.12.jar:5.3.12]
	at com.cxstar.business.service.impl.EBookCollectionServiceImpl.delete(EBookCollectionServiceImpl.java:304) ~[classes/:na]
	at com.cxstar.api.business.controller.collection.EBookCollectionController.delete(EBookCollectionController.java:105) ~[classes/:na]
	at com.cxstar.api.business.controller.collection.EBookCollectionController$$FastClassBySpringCGLIB$$5a53a40a.invoke(<generated>) ~[classes/:na]
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.12.jar:5.3.12]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:783) ~[spring-aop-5.3.12.jar:5.3.12]

problem analysis:

The meaning of the error message is: the number of commit or rollback calls for each transaction should not exceed once, and after the try-catch catches an exception and performs rollback, the finally commit method is executed

Error scene

Common code errors are as follows:

try{
    
    

	//业务代码,执行增改查
	
}catch ( Exception e){
    
    
      transactionManager.rollback(transactionStatus);
 }finally {
    
    
      transactionManager.commit(transactionStatus);
}

If an error is reported in the business code, it will be caught by the catch and the transaction will be rolled back, but the method of finally commit will be executed at the end, which will cause this problem to occur

solution

1. After executing rollback, directly throw an exception to exit the currently executing method

try{
    
    
	//业务代码,执行增改查
}catch ( Exception e){
    
    
      transactionManager.rollback(transactionStatus);
      throw new BusinessException(e.getMessage());
 }finally {
    
    
      transactionManager.commit(transactionStatus);
}

2. Remove finally and put the commit method of transaction submission before catch

try{
    
    
	//业务代码,执行增改查
	transactionManager.commit(transactionStatus);
}catch ( Exception e){
    
    
     transactionManager.rollback(transactionStatus);
     throw new BusinessException(e.getMessage());
}

Guess you like

Origin blog.csdn.net/qq_29864051/article/details/130450921