我习惯于在hibernate 3中使用getHibernateTemplate(),现在我正在转向Hibernate 4,在这里我没有找到以下类:
org.springframework.orm.hibernate4.support.HibernateDaoSupport;
在这里我读过关于它不建议使用
有人可以解释我为什么吗?现在我需要执行所有任务,如提交,关闭,刷新由getHibernateTemplate()方法自动管理的事务吗?
答案 0 :(得分:38)
因为它的主要目标是将Hibernate会话绑定到当前的Spring事务,而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会自动完成该会话。