getHibernateTemplate() VS getSession()

如題所示,對於這個問題,官網文檔已給出答案,詳見:

/**
     * Obtain a Hibernate Session, either from the current transaction or
     * a new one. The latter is only allowed if the
     * {@link org.springframework.orm.hibernate3.HibernateTemplate#setAllowCreate "allowCreate"}
     * setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is "true".
     * <p><b>Note that this is not meant to be invoked from HibernateTemplate code
     * but rather just in plain Hibernate code.</b> Either rely on a thread-bound
     * Session or use it in combination with {@link #releaseSession}.
     * <p>In general, it is recommended to use HibernateTemplate, either with
     * the provided convenience operations or with a custom HibernateCallback
     * that provides you with a Session to work on. HibernateTemplate will care
     * for all resource management and for proper exception conversion.
     * @return the Hibernate Session
     * @throws DataAccessResourceFailureException if the Session couldn't be created
     * @throws IllegalStateException if no thread-bound Session found and allowCreate=false
     * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
     */
org.springframework.orm.hibernate3.support.HibernateDaoSupport#getSession()

Spring推薦我們使用HibernateTemplate,如有必要,則通過HibernateCallback來調用原生Session。

推薦原因,HibernateTemplate可以幫助我們進行資源管理和適當的異常轉換!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章