Spring Hibernate 配置声明式事务无效

在工程的spring配置文件里量配置了声明式事务,但测试时却不回滚,异常后仍然会保存部分数据。 

1、首先,想到的是配置是否正确,事务是否给加上了。 

使用:

  1. <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>  
  2.   
  3. Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();  
  4.   
  5. Query q = session.createSQLQuery("select * from T_SQUENCE");  
  6. 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"/> 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值