因爲它的主要目標是獲得與當前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自動完成。
見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