Spring+Hibernate 异常No Hibernate Session bound to thread, and configuration does not allow creation

异常

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here


错误原因:

通常用sessionFactory的getCurrentSession()方法获取当前线程中绑定的session出现这个异常,而使用sessionFactory.openSession()得到session对象就没有这个异常;因为使用getCurrentSession得到当前线程的session是通过当前的事务产生的,产生如上的错误是因为没有配置事务,或者不在事务管理的范围内
若没有配置事务,当前线程中就没创建session,则出现以上信息。openSession的中的session需要自己手动去管理,关闭;


Spring的getHibernateTemplate().getSessionFactory().getCurrentSession()的意思是得到当前线程绑定的session,因为在hibernate.cfg.xml或者beans.xml已经配置了current_session_context_class的值为thread,而当前线程绑定的session是通过当前的事务产生的,如果没有配置事务的话,当前线程threadlocal中就不存在 session,这样就出现no session Exception。
      有点恍然大悟了。
        在工程中,spring配置的事务中,都是以"add"开头的方法进行事务处理,再检查自己的方法名称,都是自定义的,不是以"add"开头的。还有可能就是在Aop中定义pointcut的规则排除了需要事务的那个包

-------------------------------------------------------------------------------------------------------------------------------------------------

<!-- 配置事务管理器 --> 
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<!--HibernateTransactionManagerBean需要依赖注入一个SessionFactorybean的引用-->
<property name = "sessionFactory" ref="sessionFactory" />
</bean>



<!-- 事务的传播特性 --> 
<tx:advice id="txAdvice" transaction-manager="transactionManager"> 
    <tx:attributes> 
     <tx:method name="add*" propagation="REQUIRED"/> 
     <tx:method name="del*" propagation="REQUIRED"/> 
     <tx:method name="modify*" propagation="REQUIRED"/> 
     <tx:method name="*" propagation="REQUIRED" read-only="true"/> 
    </tx:attributes> 
</tx:advice>

<!-- 哪些类哪些方法使用事务 --> 
     <aop:config> 
          <aop:pointcut expression="execution(* cw.ok.hibernate.*.*(..))" id="transactionPC"/> 
          <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPC"/> 
     </aop:config>



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值