Spring管理事务异常回滚的问题
项目被测试出批量更新报错,有部分数据还是被更新了....这可是重大bug啊。。
找了原因是Spring管理的hibernate事务中途发生异常没有被回滚。
一直没太重视,还以为Spring 会处理好事务
于是 写了个测试。
Users pojo
private Long id; private String cod; private String name; private String sex; private int age;
Users u1 = new Users("y0071","A1","F",18); Users u2 = new Users("y0072","A2","F",14); Users u3 = new Users("y0073","A3","F",13); Users u4 = new Users("y0074","A4","a",12); Users u5 = new Users("y0075","A5","F",11); List<Users> list = new ArrayList(); list.add(u1); list.add(u2); list.add(u3); list.add(u4); list.add(u5);
业务处理
public String addUser(List<Users> users)throws Exception{ // hibernateTemplate.saveOrUpdateAll(users); for(int i=0 ; i <users.size(); i++){ hibernateTemplate.save(users.get(i)); if(i==2){ // throw new Exception( "234234" ); String as = "asdas"; int a = Integer.parseInt(as); } } return "end"; }
applicationContext.xml 事务管理
<!-- AOP 方法的事务管理 rollback-for="Exception" propagation="REQUIRED" --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFacory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="add*" read-only="false" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.ship.service.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="txAdvice" /> </aop:config>
具体测试过程不详细记录了
结果是:
1.在事务方法中不能使用try{}catch(){} 处理异常,如果使用了,等于说你自己已经处理了异常, Spring捕获不到异常 ,不会帮你回滚,也就是可能部分做了更新。
2.如果你执意,要加try{}catch 来捕获异常,那你必须在 catch 中抛出异常,
如果抛出普通Exception ,, 不帮你回滚。
如果抛出 RuntimeException , Spring会帮你回滚。
如果抛出普通Exception 并且想要回滚, 那就必须在aop事务配置中加上 rollback-for="Exception" , spring 才会帮你处理回滚。
以后注意不要在事务方法中随便处理异常。
浙公网安备 33010602011771号