區別
getHibernateTemplate().getSessionFactory().openSession()
getHibernateTemplate().getSessionFactory().getCurrentSession()
?
?
getCurrentSession ()??
使用當前的
session
openSession()????????
重新建立一個新的
session
?
-------------------------
SessionFactory.getCurrentSession()
是
Hibernate
應用獲取
Session
的常用方法。在調用該方法時,
Hibernate
會從
interface CurrentSessionContext
獲取當前的
Session
,這是
Hibernate
在不同組件中傳遞
Session
的方法。
?
CurrentSessionContext
有三個實現,分別是
ThreadLocalSessionContext
、
JTASessionContext
和
ManagedSessionContext
。
?
ThreadLocalSessionContext
將
Session
與當前線程綁定,是使用較多的一種方案;
JTASessionContext
將
Session
與
JTA
事務綁定,在
JTA
環境中使用;
?
ManagedSessionContext
使應用可以通過
bind()
和
unbind()
方法控制
Session
的綁定,主要在有
Conversation
的應用中使用(如果使用
ManagedSessionContext
,開發人員要做的事情還是很多的)。
?
CurrentSessionContext
實現的選擇可以通過
hibernate.current_session_context_class
來配置。
?
另一種更常見的創建
Session
的方法是
openSession()
。
?
?
openSession()
與
getCurrentSession()
有何不同和關聯呢?
?
在
SessionFactory
啟動的時候,
Hibernate
會根據配置創建相應的
CurrentSessionContext
,在
getCurrentSession()
被調用的時候,實際被執行的方法是
CurrentSessionContext.currentSession()
。在
currentSession()
執行時,如果當前
Session
為空,
currentSession
會調用
SessionFactory
的
openSession
。所以
getCurrentSession()
對于
Java EE
來說是更好的獲取
Session
的方法。
?
再說
ManagedSessionContext
,它提供了更靈活的綁定
Session
的方式,但是使用起來去不簡單。
在
Hibernate
的
CaveatEmptor
實例中有關于使用
ManagedSessionContext
的例子,但更好的選擇是使用
Seam Framework
。
?