HibernateException: No Hibernate Session bound to thread


解决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()方法引发的异常问题解决!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM