Spring 4 + Hibernate 4 下 getCurrentSession()的使用情况

前言:1 getCurrentSession创建的session会和绑定到当前线程,而openSession不会。

    2 getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭

    这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置

      * 如果使用的是本地事务(jdbc事务)
    <property name="hibernate.current_session_context_class">thread</property>
  * 如果使用的是全局事务(jta事务)
    <property name="hibernate.current_session_context_class">jta</property> 

本人新手,在整合Spring 4.x  + Hibernate 4.x 时想用 getCurrentSession()来获取session,然后并不是 一句sessionFactory.getCurrentSession()就简单解决的。。。。。

  在其他配置都已完成的情况下加上 

                      spring管理事务

            获取session。。。。。执行save(e)方法。。。。

           Error  

  百度后发现,原因出现在 hibernate.current_session_context_class = thread 这句话上。当单独使用hibernate的时候,这句话就起作用了。在使用本地JDBC事务下,此时的创建的session就会被绑定到当前线程中。而我之前在配置的时候使用的是spring来管理事务,所以报错。

              : 

 

        Error  "No Session found for current thread"

           百度发现:SessionFactory的getCurrentSession并不能保证在没有当前Session的情况下会自动创建一个新的,这取决于 CurrentSessionContext的实现,SessionFactory将调用CurrentSessionContext的 currentSession()方法来获得Session。在Spring中,如果我们在没有配置TransactionManager并且没有事先调 用SessionFactory.openSession()的情况直接调用getCurrentSession(),那么程序将抛出“No Session found for current thread”异常

        之前我已经配置过TransactionManager了,怎么还会报错呢?   最后发现原来之前的配置  expression表达式写错了。。。细节决定成败!

 

posted @ 2015-11-27 16:53  wandy丶  阅读(3014)  评论(0编辑  收藏  举报