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

  • 相关阅读:
    使用Spring提供的缓存抽象机制整合EHCache为项目提供二级缓存
    Spring使用Cache、整合Ehcache(转)
    每天学习SQL
    多线程
    ### The error may involve defaultParameterMap ### The error occurred while setting parameters
    日志分表
    Quartz学习(转)
    Quartz中时间表达式的设置-----corn表达式 (转)(http://www.cnblogs.com/GarfieldTom/p/3746290.html)
    分享一个测试图片的方式
    阿里云ECS配置踩坑之路
  • 原文地址:https://www.cnblogs.com/ylhssn/p/5181149.html
Copyright © 2011-2022 走看看