Spring MyBatis 事务配置不回滚
spring 和 mybatis 项目配置的事务 不回滚研究了一下有以下几个原因:
1. mysql(我用的mysql) 表的 引擎 不是 InnoDB (因为InnoDB是支持事务的)
2. 抛出的异常 是 Exception不是 RuntimeException 因为 spring 的异常默认是检查(unhandled Exception)
3. 配置的方法是否正确:
下面是我的一个配置,留下来以便查询
<!-- transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- enable component scanning (beware that this does not enable mapper
scanning!) -->
<context:component-scan base-package="com.auto"/>
<!-- enable autowire -->
<context:annotation-config />
<!-- enable transaction demarcation with annotations -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*"read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="list*" read-only="true"/>
<tx:method name="*" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<!-- ensure that the above transactional advice runs for any execution of
an operation defined by the FooService interface -->
<aop:config proxy-target-class="true">
<aop:pointcut id="fooServiceOperation"
expression="execution(* com.auto.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation" />
</aop:config>
------------------------------------------------------------------
下面是 看到别的可能 我没有经过验证 贴出来 有时间验证一下:
配置文件的问题吧?
1.root-context.xml
<!-- 不扫描带有@Controller注解的类。因为这些类已经随容器启动时,在servlet-context中扫描过一遍了 -->
<context:component-scan base-package="com.kimho">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
2、servlet-context.xml:
<!-- 扫描业务组件,让spring不扫描带有@Service注解的类(留在root-context.xml中扫描@Service注解的类),防止事务失效 -->
<context:component-scan base-package="com.kimho">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
Spring MVC启动时的配置文件,包含组件扫描、url映射以及设置freemarker参数,让spring不扫描带有@Service注解的类。为什么要这样设置?因为servlet-context.xml与service-context.xml不是同时加载,如果不进行这样的设置,那么,spring就会将所有带@Service注解的类都扫描到容器中,等到加载service-context.xml的时候,会因为容器已经存在Service类,使得cglib将不对Service进行代理,直接导致的结果就是在service-context中的事务配置不起作用,发生异常时,无法对数据进行回滚。
页:
[1]