spring 事务不起作用 问题汇总

 今早接手了别人的项目,测试了一下事务,发觉不起作用,检查了N久代码,才发觉是springMVC 配置文件里context:component-scan重复扫码了service,导致事务不起作用(建议MVC scan只扫描action或Controller),下面根据网上的一些资料,整理了一下事务不起作用的几个点:

1、首先使用如下代码 确认你的bean 是代理对象吗?

AopUtils.isAopProxy()

AopUtils.isCglibProxy() //cglib

AopUtils.isJdkDynamicProxy() //jdk动态代理

如果不是 那么就是切入点配置出错了 或者如果你使用了springmvc,可能是context:component-scan重复扫描引起的:
http://jinnianshilongnian.iteye.com/blog/1423971

http://jinnianshilongnian.iteye.com/blog/1762632

http://jinnianshilongnian.iteye.com/blog/1857189

2、如果是aop代理,那么说明代理成功,那么可能是如使用mysql且引擎是MyISAM造成的(因为不支持事务),改成InnoDB即可。

3、 如果你是基于类的代理,而非接口,如果想代理父类里的,可以用

execution(* com.sishuok.es..service..+.(..))

//+表示子类的也扫描(参考http://jinnianshilongnian.iteye.com/blog/1420691

4、spring事务默认只在发生未被捕获的 RuntimeExcetpion时才回滚,所以,得检查service方法中有没有使用try catch,如果使用了try catch,在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚,或在service层方法的catch语句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常(最好不要在service中try catch)

5.针对默认 只在发生未被捕获RuntimeExcetpion时才回滚的情况,可以重设一下exception回滚策略
rollback-for=”java.lang.Exception”

 <tx:advice id="tx"  transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="add*"    propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
        </tx:attributes>
    </tx:advice>

总结前三点来自:http://jinnianshilongnian.iteye.com/blog/1850432

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值