spring 配置声明式事务:
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- <property name="dataSource" ref="dataSource"/>-->
<constructor-arg index="0" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务的切入 -->
<aop:config>
<aop:pointcut id="txPoint" expression="execution(* online.zzkweb.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
正常情况下,以上的配置是可成功的开启声明式事务,并且事务执行过程中发生错误是可以回滚的。
当然,事情的发展往往可能没有这么顺利:发生错误但是没有回滚
情况一:给方法配置事务可能不全面
可能你配置是这样的
<tx:attributes>
<tx:method name="select*"/>
<tx:method name="update*" />
<tx:method name="delete*"/>
</tx:attributes>
为了验证是否配置全面:
1、可以通过日志来检查:
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4b8729ff] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.jdbc.JDBC4Connection@37fb0bed] will not be managed by Spring
注意重点: will not be managed by Spring
也就是说不是配置错误就是配置错了,为了快速验证是不是配置问题,可以把代码改为:
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
再次运行,查看日志,发现是
Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6b6776cb]
JDBC Connection [com.mysql.jdbc.JDBC4Connection@4b5189ac] will be managed by Spring
will be managed by Spring 说明Spring事务已经被spring管理了。因此说明是某些方法没有配置全。
关于<tx:method name="*"/>
的propagation
参数默认是REQUIRED
用得最多的也是REQUIRED
所以propagation="REQUIRED"
可写可不写。
如果这时候发现发生错误时,会发生回滚,那很幸运spring配置声明式事务就此成功。如果还是不会回滚,那就是数据库的问题了,详见情况二。
情况二、数据库中表的引擎
Mysql 中 InnoDB 支持事务,MyISAM 不支持事务。
所以,在代码完全正确的情况下,事务不回滚,那就说明你的数据库中表的引擎为 MyISAM,只需要把它改为 InnoDB 就行。
use mybatis; # 我的数据库叫 mybatis
show create table users; # mybatis 里面有一个叫 users 的表
从图中可以看到mybatis的users表的引擎确实是MyISAM。改他。
alter table users engine=InnoDB; # 修改users表的引擎
show create table users; # 再次查看引擎
这时候运行代码发现发生错误时,发生回滚。
OK!
spring配置声明式事务OVER!