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

  • 相关阅读:
    【XSY3309】Dreamweaver 高斯消元 拉格朗日插值
    【LUOGU???】WD与地图 整体二分 线段树合并
    【CSA49F】【XSY3317】card 博弈论 DP
    【CSA72G】【XSY3316】rectangle 线段树 最小生成树
    【CSA49G】【XSY3315】jump DP
    【集训队作业2018】【XSY3372】取石子 DP
    【LUOGU???】WD与数列 sam 启发式合并
    【LUOGU???】WD与积木 NTT
    【AGC030F】Permutation and Minimum DP
    【AGC030D】Inversion Sum DP
  • 原文地址:https://www.cnblogs.com/ylhssn/p/5181149.html
Copyright © 2020-2023  润新知