2013-07-29 123 views
1

我在這個項目中使用Hibernate和Spring MVC。(Hibernate)Session.close()和releaseSession(Session)之間的區別

我有這樣一段代碼:

... 

int count = (Integer) this.getSession().createSQLQuery(sql).list().get(0); 

this.getSession().close(); 

return count; 

我應該使用this.getSession.close(),還是應該使用releaseSession(this.getSession()) ??

有I'm煩惱理解這兩種方法之間的區別..

謝謝!

+0

這個魔術'releaseSession'方法來自哪裏? –

+0

http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/orm/hibernate3/support/HibernateDaoSupport.html#releaseSession(org.hibernate.Session) –

+3

那麼你的答案是: _關閉給定的Hibernate Session,通過這個DAO的SessionFactory創建**,如果它沒有綁定到線程**(即不是事務性會話)._(強調增加)。 'close'方法**總是**關閉'session'。如果需要,'releaseSession'方法只會關閉'session'。如果你關閉了一個線程綁定的會話,那麼你的應用程序中的其他地方就會出現問題,因爲Spring並不期望它被關閉。 –

回答

2

HibernateDaoSupport是Spring框架提供的支持,當releaseSession()被調用時,它只會終止hibernate會話,而不是事務。但是當你執行hibernate的session.close()時,它也會終止事務。我認爲你不需要自己處理這些交易。讓春天來處理它們吧。 @Transactional會處理它們。只需在需要的地方定義它。