Hibernate在使用的時候需要通過SessionFactory打開一個session,而目前獲取session我們有兩種方式,openSession和getCurrentSession,如下:
Configuration config = new Configuration();
SessionFactory sessionFactory = config.buildSessionFactory();
//方式一
Session session1 = sessionFactory.openSession();
//方式二
Session session2 = sessionFactory.getCurrentSession();
兩種方法的區別如下:
(1)openSession每次打開都是新的Session,所以多次獲取的Session實例是不同的,並且需要人爲的調用close方法進行Session關閉。
(2)getCurrentSession是從當前上下文中獲取Session並且會綁定到當前線程,第一次調用時會創建一個Session實例,如果該Session未關閉,後續多次獲取的是同一個Session實例;事務提交或者回滾時會自動關閉Sesison,無需人工關閉。
使用getCurrentSession時,需要在配置文件中添加如下:
(1)如果使用的是本地事務(JDBC事務)
<property name="current_session_context_class">thread</property>
(2)如果使用的是全局事務(JTA事務)
<property name="current_session_context_class">jta</property>