为什么不推荐使用 HibernateTemplate? [英] Why HibernateTemplate isn't recommended?

查看:41
本文介绍了为什么不推荐使用 HibernateTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于在 hibernate 3 中使用 getHibernateTemplate(),现在我正在转向 Hibernate 4,在这里我没有找到以下课程:

I was used to getHibernateTemplate() in hibernate 3, and now I am moving to Hibernate 4 for and here I didn't find following class:

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

这里我读过关于它不推荐使用

And here I had read about it is not more recommended to use

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

谁能解释一下为什么?在休眠 4 中,我现在需要完成所有任务,例如提交、关闭、刷新由 getHibernateTemplate() 方法自动管理的事务吗?

Can someone explain me why? and in hibernate 4 will now I need to do all task like commiting, close, flushing the transaction which was automatically managed by getHibernateTemplate() method?

推荐答案

因为它的主要目标是获得一个与当前 Spring 事务绑定的 Hibernate 会话,而 SessionFactory.getCurrentSession() 没有存在.由于它现在存在(并且很长一段时间内:即使在 hibernate3 包中也不鼓励使用 HibenateTemplate),因此没有理由使用这个 Spring 特定的类而不是使用 SessionFactory.getCurrentSession() 来获取与当前 Spring 事务相关的会话.

Because its main goal was to get a Hibernate session tied to the current Spring transaction, when SessionFactory.getCurrentSession() didn't exist. Since it now exists (and for a long time: HibenateTemplate usage is discouraged even in the hibernate3 package), there is no reason to use this Spring-specific class instead of using SessionFactory.getCurrentSession() to get a session tied to the current Spring transaction.

如果你使用 Spring,那么你应该使用它的声明式事务管理,它允许你避免打开、提交、关闭和刷新.这一切都由 Spring 自动完成:

If you use Spring, then you should use its declarative transaction management, which allows you to avoid opening, committing, closing and flushing. It's all done by Spring automatically:

@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 自动完成.

In the above example, a transaction will be started (if not already started) before the method invocation; A session will be created by Spring for the transaction, and the session will be automatically flushed before the commit of the transaction, that will be done by Spring automatically when the method returns.

这篇关于为什么不推荐使用 HibernateTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆