2011-07-13 26 views

回答

1

在一個配置良好的Spring應用程序中,兩者在一種情況下是等價的:當沒有當前的事務上下文時。在這種情況下,getCurrentSession()將不起作用,而使用HibernateCallback將爲您打開會話和Hibernate事務並在最後關閉它們。

注意the documentation of HibernateTemplate提到的getCurrentSession()應優選的:

注意:作爲休眠3.0.1的,事務的Hibernate訪問代碼可以 也可以以純的Hibernate風格編碼。因此,對於新開始的 項目,請考慮採用基於 SessionFactory.getCurrentSession()的代碼的標準Hibernate3風格編碼 數據訪問對象。

它還說:

注意的HibernateTemplate將執行自己的會話管理, 不參與自定義休眠CurrentSessionContext除非 你明確地切換「allowCreate」爲「假」。

混合兩種做法是不是一個好主意。

我的首選是避免HibernateTemplate,直接使用Hibernate Session API,並使用Spring管理的聲明式事務。

+0

@Nizet:謝謝你。我想我會用Hibernate3風格。 –