2013-08-01 256 views
16

我是用getHibernateTemplate()在休眠3,現在我移動到Hibernate 4,在這裏我沒有找到下面的類:爲什麼不推薦HibernateTemplate?

org.springframework.orm.hibernate4.support.HibernateDaoSupport; 

在這裏,我已經讀到它是不是更推薦使用

http://forum.springsource.org/showthread.php?117227-Missing-Hibernate-Classes-Interfaces-in-spring-orm-3.1.0.RC1

有人能解釋我爲什麼? 在hibernate 4中,現在我需要完成所有任務,比如提交,關閉,刷新由getHibernateTemplate()方法自動管理的事務?

+0

見http://stackoverflow.com/questions/4067775/spring-hibernate-template-when-to-use-and-why/4067801#4067801 和 http://stackoverflow.com/questions/ 5104765/hibernatedaosupport-not-recommended-why/5104965#5104965 – StormeHawke

回答

37

因爲它的主要目標是獲得與當前Spring交易相關的Hibernate會話,所以當SessionFactory.getCurrentSession()不存在時。由於它現在存在(並且很長一段時間:即使在hibernate3包中也不鼓勵使用HibenateTemplate),所以沒有理由使用這個Spring特定的類而不是使用SessionFactory.getCurrentSession()來獲得與當前Spring事務綁定的會話。

如果你使用Spring,那麼你應該使用它的聲明式事務管理,它允許你避免打開,提交,關閉和刷新。這一切都被Spring自動完成:

@Autowired 
private SessionFactory sessionFactory; 

@Transactional 
public void someMethod() { 
    // get the session for the current transaction: 
    Session session = sessionFactory.getCurrentSession(); 
    // do things with the session (queries, merges, persists, etc.) 
} 

在上面的例子中,一個事務將要啓動的方法調用之前(如果尚未啓動); Spring會爲事務創建一個會話,並且會話將在事務提交之前自動刷新,這將在方法返回時由Spring自動完成。

+0

查詢情況如何?我必須在查詢方法上添加@Transactional嗎? – Hippoom

+0

是的。每個Hibernate交互都應該在一個事務中完成。 –

+0

如果我們使用sessionFactory.getCurrentSession()獲取會話,那麼執行查詢後我們是否需要關閉會話(session.close())?或者它會在春天自動完成。 – user1919581

相關問題