Spring exception capture and rollback transaction solution

By default, spring only rolls back when there is an uncaught runtimeexcetpion.

The most stupid way: code-level control: TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Why is it not rolled back when rollba-for="java.lang.Exception" is configured in aop advitor?

problem solved:

Principle: Spring aop exception capture principle: the intercepted method needs to explicitly throw an exception, and it cannot be processed in any way, so that the aop agent can catch the exception of the method and roll back. By default, aop only captures the exception of runtime exception. But you can capture specific exceptions and rollback through the configuration of
<tx:method name="upd*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>

In other words, do not use try catch in the service method or add throw new runtimeexcetpion() at the end of the catch, so that when the program is abnormal, it can be caught by aop and then rolled back

solution:

Solution 1. For example, the service layer handles transactions, then the method in the service does not do exception capture, or the throw new RuntimeException() statement is added at the end of the catch statement, so that the aop catches the exception and then rolls back, and in the service upper layer (webservice Client, view layer action) to continue to catch this exception and deal with it

Option 2. Add in the catch statement of the service layer method: TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); statement, manual rollback, so that the upper layer does not need to deal with exceptions (the current project approach)

<bean id="transactionManager"
 class="org.springframework.orm.hibernate3.HibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
 <tx:attributes>
  <tx:method name="add*" propagation="REQUIRED" />
  <tx:method name="upd*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
  <tx:method name="del*" propagation="REQUIRED" />
  <tx:method name="*" propagation="SUPPORTS" />
 </tx:attributes>
</tx:advice>

<aop:config>
 <aop:pointcut id="canyin" expression="execution(* com.laphone.base.baseservice.*.*(..)) ||execution(* com.laphone.canyin.*.service.*.*(..)) || execution(* com.laphone.canyin.*.*.service.*.*(..))"/>
 <aop:advisor advice-ref="txAdvice" pointcut-ref="canyin" />
</aop:config>

Life is more than perseverance and hard work. Dreams are meaningful pursuits.
Finally, I wish you all early success in your studies, get a satisfactory offer, get a quick promotion and raise your salary, and reach the pinnacle of life.
If you need courseware source code software and other materials to add a small assistant vx: xcw18874131605 (note: CSDN

Guess you like

Origin blog.csdn.net/p1830095583/article/details/115255606