[Java]Spring事务失效的几种原因

 5种大的原因

 1.如使用mysql且引擎是MyISAM,则事务会不起作用,原因是MyISAM不支持事务,可以改成InnoDB

假如有兴趣了解 MySQL中 ” engine=innodb ” 以及 ” engine=innodb 和engine=myisam的区别 “,可以读读这篇文章:http://blog.sina.com.cn/s/blog_6ac4c6cb01018pb1.html

可使用下述语句之一检查表的标类型: 

SHOW TABLE STATUS LIKE 'tbl_name';
SHOW CREATE TABLE tbl_name;
例如,要想确定InnoDB存储引擎是否可用,可检查have_innodb变量的值。


2. 如果使用了spring+mvc,则context:component-scan重复扫描问题可能会引起事务失败。
3. @Transactional 注解开启配置,必须放到listener里加载,如果放到DispatcherServlet的配置里,事务也是不起作用的。
4. @Transactional 注解只能应用到 public 可见度的方法上。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错,事务也会失效。
5. Spring团队建议在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。在接口上使用 @Transactional 注解,只能当你设置了基于接口的代理时它才生效。因为注解是 不能继承 的,这就意味着如果正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装。

需要注意的事项

Spring的Transactional的API文档:

If no rules are relevant to the exception, it will be treated like DefaultTransactionAttribute (rolling back on runtime exceptions).

在业务代码中,有如下两种情况,比如:
throw new RuntimeException(“xxxxxxxxxxxx”); 事务回滚
throw new Exception(“xxxxxxxxxxxx”); 事务没有回滚

spring内部catch的就是 RuntimeException, service抛出RuntimeException可以回滚
如果抛出Exception,就不回滚….

  • 1).Spring的AOP即声明式事务管理默认是针对unchecked exception回滚。也就是默认对RuntimeException()异常或是其子类进行事务回滚;checked异常,即Exception可try{}捕获的不会回滚,如果使用try-catch捕获抛出的unchecked异常后没有在catch块中采用页面硬编码的方式使用spring api对事务做显式的回滚,则事务不会回滚, “将异常捕获,并且在catch块中不对事务做显式提交=生吞掉异常” ,要想捕获非运行时异常则需要如下配置:

解决办法:
1.在针对事务的类中抛出RuntimeException异常,而不是抛出Exception。
2.在txAdive中增加rollback-for,里面写自己的exception,例如自己写的exception:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
     <tx:method name="*" rollback-for="com.cn.untils.exception.XyzException"/>
   </tx:attributes>
 </tx:advice>

或者定义不会滚的异常

<tx:advice id="txAdvice">
    <tx:attributes>
       <tx:method name="update*" no-rollback-for="IOException"/>
       <tx:method name="*"/>
    </tx:attributes>
 </tx:advice>
  • 2).spring的事务边界是在调用业务方法之前开始的,业务方法执行完毕之后来执行commit or rollback(Spring默认取决于是否抛出runtime异常).
    如果抛出runtime exception 并在你的业务方法中没有catch到的话,事务会回滚。
    一般不需要在业务方法中catch异常,如果非要catch,在做完你想做的工作后(比如关闭文件等)一定要抛出runtime exception,否则spring会将你的操作commit,这样就会产生脏数据.所以你的catch代码是画蛇添足。

    如:

try {  
    //bisiness logic code  
} catch(Exception e) {  
    //handle the exception  
}  

由此可以推知,在spring中如果某个业务方法被一个 整个包裹起来,则这个业务方法也就等于脱离了spring事务的管理,因为没有任何异常会从业务方法中抛出!全被捕获并吞掉,导致spring异常抛出触发事务回滚策略失效。
不过,如果在catch代码块中采用页面硬编码的方式使用spring api对事务做显式的回滚,这样写也未尝不可。

  • 3).基于注解的事务:

    Transactional的异常控制,默认是Check Exception 不回滚,unCheck Exception回滚
    如果配置了rollbackFor 和 noRollbackFor 且两个都是用同样的异常,那么遇到该异常,还是回滚
    rollbackFor 和noRollbackFor 配置也许不会含盖所有异常,对于遗漏的按照Check Exception 不回滚,unCheck Exception回滚


如果只是@Transactional失效的话,可以考虑改成:@Transactional(rollbackFor=Exception.class)

例子如下,在注释的代码上加入:

@Transactional(value="transactionManager", rollbackFor=java.lang.Exception.class)

或者:

@Transactional(rollbackFor=Exception.class)

例如:
配置文件:

    <bean id="studentMGDataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${student_MG_jdbc.driver}" />  
        <property name="url" value="${student_MG_jdbc.url}" />  
        <property name="username" value="${student_MG_jdbc.username}" />  
        <property name="password" value="${student_MG_jdbc.password}" />  
        <property name="initialSize" value="${student_MG_jdbc.initialSize}" />  
        <property name="maxActive" value="${student_MG_jdbc.maxActive}" />  
        <property name="maxIdle" value="${student_MG_jdbc.maxIdle}" />  
        <property name="maxWait" value="${student_MG_jdbc.maxWait}" />  
        <property name="defaultAutoCommit" value="${student_MG_jdbc.defaultAutoCommit}" />  
    </bean>  

    <bean id="studentMGSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="configLocation" value="classpath:mybatis/mybatis-studentMG-config.xml" />  
        <property name="dataSource" ref="studentMGDataSource" />  
    </bean>  

    <bean id="studentMGSqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0" ref="studentMGSqlSessionFactory" />  
    </bean>  

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

    <tx:annotation-driven proxy-target-class="true" transaction-manager="studentMGTxManager" />  

在类中这样使用

    @Transactional(value="studentMGTxManager",rollbackFor=java.lang.Exception.class)  
    public void saveStudentDto(List<StudentDto> dtoList, String classId) {  

    }  


 5种大的原因

 1.如使用mysql且引擎是MyISAM,则事务会不起作用,原因是MyISAM不支持事务,可以改成InnoDB

假如有兴趣了解 MySQL中 ” engine=innodb ” 以及 ” engine=innodb 和engine=myisam的区别 “,可以读读这篇文章:http://blog.sina.com.cn/s/blog_6ac4c6cb01018pb1.html

可使用下述语句之一检查表的标类型: 

SHOW TABLE STATUS LIKE 'tbl_name';
SHOW CREATE TABLE tbl_name;
例如,要想确定InnoDB存储引擎是否可用,可检查have_innodb变量的值。


2. 如果使用了spring+mvc,则context:component-scan重复扫描问题可能会引起事务失败。
3. @Transactional 注解开启配置,必须放到listener里加载,如果放到DispatcherServlet的配置里,事务也是不起作用的。
4. @Transactional 注解只能应用到 public 可见度的方法上。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错,事务也会失效。
5. Spring团队建议在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。在接口上使用 @Transactional 注解,只能当你设置了基于接口的代理时它才生效。因为注解是 不能继承 的,这就意味着如果正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装。

需要注意的事项

Spring的Transactional的API文档:

If no rules are relevant to the exception, it will be treated like DefaultTransactionAttribute (rolling back on runtime exceptions).

在业务代码中,有如下两种情况,比如:
throw new RuntimeException(“xxxxxxxxxxxx”); 事务回滚
throw new Exception(“xxxxxxxxxxxx”); 事务没有回滚

spring内部catch的就是 RuntimeException, service抛出RuntimeException可以回滚
如果抛出Exception,就不回滚….

  • 1).Spring的AOP即声明式事务管理默认是针对unchecked exception回滚。也就是默认对RuntimeException()异常或是其子类进行事务回滚;checked异常,即Exception可try{}捕获的不会回滚,如果使用try-catch捕获抛出的unchecked异常后没有在catch块中采用页面硬编码的方式使用spring api对事务做显式的回滚,则事务不会回滚, “将异常捕获,并且在catch块中不对事务做显式提交=生吞掉异常” ,要想捕获非运行时异常则需要如下配置:

解决办法:
1.在针对事务的类中抛出RuntimeException异常,而不是抛出Exception。
2.在txAdive中增加rollback-for,里面写自己的exception,例如自己写的exception:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
     <tx:method name="*" rollback-for="com.cn.untils.exception.XyzException"/>
   </tx:attributes>
 </tx:advice>

或者定义不会滚的异常

<tx:advice id="txAdvice">
    <tx:attributes>
       <tx:method name="update*" no-rollback-for="IOException"/>
       <tx:method name="*"/>
    </tx:attributes>
 </tx:advice>
  • 2).spring的事务边界是在调用业务方法之前开始的,业务方法执行完毕之后来执行commit or rollback(Spring默认取决于是否抛出runtime异常).
    如果抛出runtime exception 并在你的业务方法中没有catch到的话,事务会回滚。
    一般不需要在业务方法中catch异常,如果非要catch,在做完你想做的工作后(比如关闭文件等)一定要抛出runtime exception,否则spring会将你的操作commit,这样就会产生脏数据.所以你的catch代码是画蛇添足。

    如:

try {  
    //bisiness logic code  
} catch(Exception e) {  
    //handle the exception  
}  

由此可以推知,在spring中如果某个业务方法被一个 整个包裹起来,则这个业务方法也就等于脱离了spring事务的管理,因为没有任何异常会从业务方法中抛出!全被捕获并吞掉,导致spring异常抛出触发事务回滚策略失效。
不过,如果在catch代码块中采用页面硬编码的方式使用spring api对事务做显式的回滚,这样写也未尝不可。

  • 3).基于注解的事务:

    Transactional的异常控制,默认是Check Exception 不回滚,unCheck Exception回滚
    如果配置了rollbackFor 和 noRollbackFor 且两个都是用同样的异常,那么遇到该异常,还是回滚
    rollbackFor 和noRollbackFor 配置也许不会含盖所有异常,对于遗漏的按照Check Exception 不回滚,unCheck Exception回滚


如果只是@Transactional失效的话,可以考虑改成:@Transactional(rollbackFor=Exception.class)

例子如下,在注释的代码上加入:

@Transactional(value="transactionManager", rollbackFor=java.lang.Exception.class)

或者:

@Transactional(rollbackFor=Exception.class)

例如:
配置文件:

    <bean id="studentMGDataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${student_MG_jdbc.driver}" />  
        <property name="url" value="${student_MG_jdbc.url}" />  
        <property name="username" value="${student_MG_jdbc.username}" />  
        <property name="password" value="${student_MG_jdbc.password}" />  
        <property name="initialSize" value="${student_MG_jdbc.initialSize}" />  
        <property name="maxActive" value="${student_MG_jdbc.maxActive}" />  
        <property name="maxIdle" value="${student_MG_jdbc.maxIdle}" />  
        <property name="maxWait" value="${student_MG_jdbc.maxWait}" />  
        <property name="defaultAutoCommit" value="${student_MG_jdbc.defaultAutoCommit}" />  
    </bean>  

    <bean id="studentMGSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="configLocation" value="classpath:mybatis/mybatis-studentMG-config.xml" />  
        <property name="dataSource" ref="studentMGDataSource" />  
    </bean>  

    <bean id="studentMGSqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0" ref="studentMGSqlSessionFactory" />  
    </bean>  

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

    <tx:annotation-driven proxy-target-class="true" transaction-manager="studentMGTxManager" />  

在类中这样使用

    @Transactional(value="studentMGTxManager",rollbackFor=java.lang.Exception.class)  
    public void saveStudentDto(List<StudentDto> dtoList, String classId) {  

    }  


猜你喜欢

转载自blog.csdn.net/drdongshiye/article/details/80771403