zoukankan      html  css  js  c++  java
  • 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()方法引发的异常问题解决!

  • 相关阅读:
    基于shell脚本比较数字加减乘除 要bc计算器
    基于shell脚本比较数字大小
    备份WordPress
    在CentOS 7 安装没有mysql
    SQL中判断字符串中包含字符的方法
    ASP.NET生成的HTML代码
    win7禁用休眠,献给c盘空间不足的朋友.
    SQLServer2005和2008的分页技术比较[转]
    浏览器兼容性系列--浅谈window.attachEvent
    在ASP.NET 的服务器端控件中有三种关于 ID 的属性
  • 原文地址:https://www.cnblogs.com/ylhssn/p/5181149.html
Copyright © 2011-2022 走看看