项目中遇到一个问题:
执行service层的方法时出错抛出异常,使用了try catch进行了捕捉,并在catch中设置了收到回滚,发现事务回滚出错:
No transaction aspect-managed TransactionStatus in scope
由于之前写过一个方法,也是在catch中进行手动回滚,事务是可以正常回滚的,对比之后没有发现什么不一样的地方。
后来在网上看到,可能是由于spring的配置文件中对事务的配置有问题,查了一下事务的传播特性的配置:
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allServiceMethod" expression="execution(* com.xx.service..service.*.*(..)) or execution(* com.xx.service..biz.*.*(..))" />
<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
</aop:config>
这里是我的spring对事务的相关配置,表示在 com.xx.service…service.或com.xx.service…biz.的类中,以save,add,update,modify,change,delete开头的方法被执行时,如果发生异常则可以回滚。
遇到的一个问题:一开始我执行的service层的方法名是以其他单词开头的,不在配置文件中的配置列中,spring无法识别这个方法是可以回滚的,在方法中我调用了其他service的方法,并且是以update开头的,但是执行的时候却报错如下:
Connection is read-only. Queries leading to data modification are not allowed
error may in update* -inline
这个错误就是由于service的该方法不支持回滚导致的。
@Transactianal注解的使用
https://blog.youkuaiyun.com/KKALL1314/article/details/96481557
这篇博客详细介绍了注解的使用方式
在方法头加@Transactional注解是针对异常抛出的情况,一旦使用try catch进行捕捉,只加这个注解就无效了,必须catch中手动回滚