2013-05-22 31 views
2

我正在嘗試使用generic-dao(http://code.google.com/p/hibernate-generic-dao/)。但是,在我的HibernateBaseDAO中,getSession()方法實現爲sessionFactory.getCurrentSession()。這導致對任何實體錯誤更新getCurrentSession()vs openSession()

org.hibernate.HibernateException: createCriteria is not valid without active transaction 

然而,當我在地方的getCurrentSession()的使用的openSession(),它的工作原理。我沒有使用spring作爲pom.xml中的依賴項。我一直在閱讀openSession()和getCurrentSession(),但仍不明白爲什麼會發生這種情況?

+0

您指定休眠使用ThreadLocalSessionContext的DAO的假設? –

+0

是的,我已經指定了ThreadLocalSessionContext – obh

回答

0

找到了解決辦法,用genericDAO它得到它必須使用的openSession()顯式地打開當前會話,同時的getCurrentSession()只是其附加到current session。據筆者

GenericDAO讓你將外部處理事務 到

0

currentSession可能會在很多情況下變得非常脆弱。

錯誤發生後,您可能會遇到未定義的狀態,因此請確保您的「當前會話」和事務未被先前的錯誤破壞。爲了達到這個目的,在使用調用DAO內的getCurrentSession之前打印出事務狀態(isActive),然後仔細檢查SessionContext是否已配置並正在工作;調用getCurrentSession兩次,並檢查是否返回實例都是一樣的,如果沒有,你可能正在尋找不同的會話:

assert getCurrentSession()==getCurrentSession() 

我學到沉痛的教訓是非常保守的休眠。所以在基礎上花費一些時間確實值得。

HTH 史蒂夫

相關問題