您的位置:首页 > 编程语言 > Java开发

spring+ mybatis 事务不能回滚问题解决

2017-04-25 13:52 656 查看
最近遇到一个回滚问题,百度了一天了,终于解决了;

百度上遇到很多中情况,我记录的情况主要是以下几点(1)错误类型是Exception,加rollback-for="excepation"就可以解决,使用try()catch(){}捕获异常你确没有把他重新抛出去,直接去掉try cathc就行(2)如果是使用aop不是注解管理事务,可能是<aop:pointcut id="confService" expression="execution(* com.cn.hnust.service.impl.*.*(..))
"/>写错(3)扫描的时候把controller和service层一起扫了,造成事务还没有配置你就开始装配了 。 

 

  我的错误类型是第三种。解决方式如下:

 我的事务管理用的是aop我贴出代码:

<tx:advice id="TestAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception.class"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="confService" expression="execution(* com.cn.hnust.service.impl.*.*(..)) "/>
<aop:advisor advice-ref="TestAdvice" pointcut-ref="confService"></aop:advisor>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"/>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>


一、首先确保你这个路径是对的

<aop:pointcut id="confService" expression="execution(* com.cn.hnust.service.impl.*.*(..)) "/>


二、在applicationControlxml(spring的配置文件)

<context:component-scan base-package="com.cn.hnust.service"></context:component-scan>

 确保有这个并且最重要的是base-pakepage="com.cn.hnust.service"
 不要只写base-pakepag="com",要精确到你那个要回滚的事务,一般是在service中,就是精确搭配service

三、在springmvc-servlet.xml(springMVC配置文件)

<context:component-scan base-package="com.cn.hnust.controller"></context:component-scan>

 

同样情况base-pakeage="com.cn.hnust.controller"
 不能只写base-package="com.cn.hnust" 要精确到controller 

主要的原理是因为:spring先加载springMVC-servlet.xml文件,如果只写base-package="com.cn.hnust也会把hnust下的service和controller同时装配进去,然而回滚是要先要扫描controller层,然后在service层,有一个先后顺序,所以在springMVC-servlet.xml中base-package后面的值要写到com.cn.hnust.controlle层,不要只写到com.cn.hnust;否则会把com.cn.hnus下的service和controller层同时扫进去,这样就造成事务管理都没有配置,你就开始装配了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: