码迷,mamicode.com
首页 > Web开发 > 详细

HibernateException: No Hibernate Session bound to thread

时间:2016-02-04 11:28:32      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

解决No Hibernate Session bound to thread

 背景交代

  在使用this.getHibernateTemplate().getSessionFactory().getCurrentSession()方法获取session时报以下异常信息:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and conf  iguration does not allow creation of non-transactional one here 

 

在SSH架构中,spring如何对事务和hibernate session进行管理

  1、getCurrentSession()是必须提交事务的。所以在用到session.getCurrentSession()的这个方法一定是要配置声明式事务管理。

  2、openSession()恰恰是与以上的方法想法,它不需要提交事务。但是他的资源必须手动关闭。

  所以针对“No Hibernate Session bound to thread”异常的解决方案有两个:

    方案一:将getCurrentSession()改为openSession()。

    方案二:在sessionFactory bean中的hibernateProperties项中配置以下信息:

1 <prop key="hibernate.current_session_context_class">
2       thread
3 </prop>
4 <prop key="hibernate.transaction.factory_class">
5   org.hibernate.transaction.JDBCTransactionFactory
6 </prop>

    在sessionFactory bean中添加以上两条配置信息后,再次运行程序,又报异常!

org.hibernate.HibernateException: createCriteria is not valid without active transaction 

   已知使用getCurrentSession()方法是必须提交事务的,而在SSH框架中是使用spring配置声明式事务管理的。

  那接下来再次复习一下spring配置声明式事务管理知识,以便查找错误。

 

spring配置声明式事务管理

此处知识回顾引自“一个无聊的人”的“Spring声明式事务配置管理方法”,博主讲的很详细,推荐一看, 传送门

以下是博文内容截图:

技术分享

 

技术分享

  除此之外还可以使用其他几种方式用spring管理事务,请自行查找资料学习。


  仔细核对项目中的配置信息后,确定事务已配置无误,当前异常信息还是未解决,继续找资料,最终在“如果你报createSQLQuery is not valid without active transaction,请看这里”一文中找到解决方式:

  将hibernate.current_session_context_class的值由Thread改为org.springframework.orm.hibernate2.SpringSessionContext

技术分享

  至此由使用getCurrentSession()方法引发的异常问题解决!

HibernateException: No Hibernate Session bound to thread

标签:

原文地址:http://www.cnblogs.com/ylhssn/p/5181149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!