1.采用getCurrentSession()創(chuàng )建的Session會(huì )綁定到當前的線(xiàn)程中去;
而采用OpenSession()則不會(huì )。
2.采用getCurrentSession()創(chuàng )建的Session在commit或rollback后會(huì )自動(dòng)關(guān)閉;
采用OpenSession()必須手動(dòng)session.close()關(guān)閉。
3.采用getCurrentSession()需要在Hibernate.cfg.xml配置文件中加入如下配置:
未綁定當前線(xiàn)程會(huì )出現異常:
org.hibernate.HibernateException:No Hibernate Session bound to thread
*如果使用的是本地事務(wù)(jdbc事務(wù))<propertyname="hibernate.current_session_context_class">thread</property>* 如果使用的是全局事務(wù)(jta事務(wù))<propertyname="hibernate.current_session_context_class">jta</property>
另外,但是在使用getCurrentSession(),必須在事務(wù)中運行,要不出
org.hibernate.HibernateException:?createQueryis not valid without active transaction
但是,配上事務(wù)后只有將
<propertyname="hibernate.current_session_context_class">thread</property>去掉,程序才能運行這不是前后矛盾么?????難道spring在通過(guò)sessionFactory獲取session時(shí),沒(méi)有調用getCurrentSession()方法。通過(guò)加入事務(wù),提交,所以不需要配置getCurrentSession?在Hibernate3.2中使用getCurrentSession,只需將其放入一個(gè)事務(wù)中即可!
聯(lián)系客服