1. 程式人生 > >openSession 和getCurrentSession的區別

openSession 和getCurrentSession的區別

1 getCurrentSession建立的session會和繫結到當前執行緒,而openSession不會。

2 getCurrentSession建立的執行緒會在事務回滾或事物提交後自動關閉,而openSession必須手動關閉

這裡getCurrentSession本地事務(本地事務:jdbc)時 要在配置檔案裡進行如下設定

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

getCurrentSession () 使用當前的session
openSession() 重新建立一個新的session 
在一個應用程式中,如果DAO 層使用Spring 的hibernate 模板,通過Spring 來控制session 的生命週期,則首選getCurrentSession ()。

openSession() 與 getCurrentSession() 有何不同和關聯呢?

在 SessionFactory 啟動的時候, Hibernate 會根據配置建立相應的 CurrentSessionContext ,在 getCurrentSession() 被呼叫的時候,實際被執行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 執行時,如果當前 Session 為空, currentSession 會呼叫 SessionFactory 的 openSession 。所以 getCurrentSession() 對於 Java EE 來說是更好的獲取 Session 的方法。


目前獲取Session的時候存在兩種方式,openSession和getCurrentSession,如下:

[java] 
  1. <span style="white-space:pre"> </span>Configuration config =new Configuration();
  2. SessionFactory sessionFactory = config.buildSessionFactory();
  3. //方式一
  4. Session session1 = sessionFactory.openSession();
  5. //方式二
  6. Session session2 = sessionFactory.getCurrentSession();
	<span style="white-space:pre">	</span>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事務)

[html] 
  1. <property name="current_session_context_class">thread</property>
<property name="current_session_context_class">thread</property>
(2)如果使用的是全域性事務(JTA事務) [html] 
  1. <property name="current_session_context_class">jta</property>