本文研究的主要是hibernate關於session的關閉,具體如下。
Student student = new Student(); student.setName("Jan"); student.setAge("22"); student.setAddress("廣東省肇慶市"); Session session =HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(student); session.flush(); session.getTransaction().commit(); 1、getCurrentSession()與openSession()的區別?
getCurrentSession()創建的session會綁定到當前線程中,而採用openSession() ,創建的session則不會getCurrentSession()創建的session在commit或rollback時會自動關閉,而採用openSession() ,創建的session必須手動關閉2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.current_session_context_class">jta</property>
openSession()與getCurrentSession()有何不同和關聯呢?
在SessionFactory 啟動的時候, Hibernate 會根據配置創建相應的CurrentSessionContext ,在getCurrentSession()被調用的時候,實際被執行的方法是CurrentSessionContext.currentSession() 。在currentSession()執行時,如果當前Session 為空, currentSession 會調用SessionFactory 的openSession 。所以getCurrentSession()對於Java EE 來說是更好的獲取Session 的方法。
許多時候出現session is close();原因就是你在hibernate.cfg.xml裡面設置了
<property name="hibernate.current_session_context_class">thread</property>
系統在commit();執行完之後就關閉了session,這時候你手動再關閉session就當然提示錯誤了
以上就是本文關於hibernate關於session的關閉實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!