thread 屬性

<property name="current_session_context_class">thread</property>
這個屬性的做用:這樣配置是本地jdbc事務配置,你經過getCurrentSession建立的session會綁定到當前線程

 

 

 

平時在單獨使用hibernate的時候,習慣於配置屬性spring

<property name="current_session_context_class">thread</property>
根據文檔,這個是hibernate3.1之後的一個新擴展,目的在於可讓咱們在某一個上下文環境(好比說當前線程)中能夠經過 SessionFactory.getCurrentSession()獲得同一個session會話.
 
後來當咱們把spring,hibernate整合的時候,在spring的主配置文件當中,咱們也習慣於帶入這樣的配置
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
,接下來在spring配置文件中,會使用spring2.x的聲明式的方式來配置事務
<tx:advice id="txAdvice" transaction-manager="transactionManager">,<aop:pointcut,<aop:advisor等等配置指定哪些方法上由spring來管理hiberante的事務,這個時候咱們試着運行一個相似於這樣的方法
public void find() {
Session se = sf.getCurrentSession();
//此處不須要se.beginTransaction(),事務已經交由spring管理
Dept d = (Dept) se.get(Dept.class, new Long(12));
}
會獲得一個異常: get is not valid without active transaction.
這個錯誤通常狀況是由於由getCurrentSession獲得的session中沒有得到的transaction,咱們通常要手動的調用se.beginTransaction(),來打開一個活動的事務.可是問題是,咱們在spring的配置文件中不是已經經過aop,指定了此處由spring來管理事務嗎,怎麼還要手動處理事務?
 
答案: 
<prop key="hibernate.current_session_context_class">thread</prop>改成
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>(默認配置)
 
參考:
1. hibernate文檔:
 
2.在hibernate中,thread,jta,manager的配置其實都是對應了3個hibernate的實現類
 
 
 
 
3.在sessionFactory配置文件中
應將hibernate.current_session_context_class設爲org.springframework.orm.hibernate3.SpringSessionContext(默認爲此值)應當把session要綁定的上下文設置爲由spring環境管理(由於咱們的事務aop也是在spring範圍中),這個時候spring中的事務配置纔會起做用(固然,之前是thread上下文環境的session,而事務託管在spring上下文中,固然spring沒法管理到thread上下文的session的事務咯)綜上所述,其實仔細看ThreadLocalSessionContext,JTASessionContext,ManagedSessionContext,SpringSessionContext咱們都會發現,他們都實現了一個接口org.hibernate.context.CurrentSessionContext關於這個接口,請參閱 org.hibernate.context.CurrentSessionContext 接口的 Javadoc,那裏有關於它的契約的詳細討論。它定義了單一的方法,currentSession(),特定的實現用它來負責跟蹤當前的上下文相關的會話 最後,咱們知道,其實線程綁定也好,上下文綁定也好,最後都是,使用實現了CurrentSessionContext接口的一個類,來跟蹤session,而後咱們經過這個類的對象來得到被它跟蹤的session,以達到在咱們定義的上下文環境中調用getCurrentSession方法得到的老是同一個session
相關文章
相關標籤/搜索