在工程的spring配置文件里量配置了声明式事务,但测试时却不回滚,异常后仍然会保存部分数据。
1、首先,想到的是配置是否正确,事务是否给加上了。
使用:
正确运行,说明DAO的方法正确的加入了事务。getCurrentSession()方式获取session需要绑定事务。
2、然后,考虑既然有事务,那异常时怎么不回滚呢?
查看Spring的文档发现下面的描述:
In its default configuration, the Spring Framework's transaction infrastructure code only marks a
transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception
is an instance or subclass of RuntimeException. (Errors will also - by default - result in a
rollback). Checked exceptions that are thrown from a transactional method do not result in rollback in
the default configuration.
默认情况下,Checked exceptions 不会回滚。
查看DAO实现,确实是捕获了异常后throw 一个自己定义的RecommendDAOException ,而这个类继承的是Exception。
3、解决问题
配置下回滚条件就行了
1、首先,想到的是配置是否正确,事务是否给加上了。
使用:
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = session.createSQLQuery("select * from T_SQUENCE");
q.list();
正确运行,说明DAO的方法正确的加入了事务。getCurrentSession()方式获取session需要绑定事务。
2、然后,考虑既然有事务,那异常时怎么不回滚呢?
查看Spring的文档发现下面的描述:
In its default configuration, the Spring Framework's transaction infrastructure code only marks a
transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception
is an instance or subclass of RuntimeException. (Errors will also - by default - result in a
rollback). Checked exceptions that are thrown from a transactional method do not result in rollback in
the default configuration.
默认情况下,Checked exceptions 不会回滚。
查看DAO实现,确实是捕获了异常后throw 一个自己定义的RecommendDAOException ,而这个类继承的是Exception。
3、解决问题
配置下回滚条件就行了
<tx:method name="*" propagation="REQUIRES_NEW" rollback-for="Throwable"/>