Java 为什么不推荐 HibernateTemplate?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18002768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:42:21  来源:igfitidea点击:

Why HibernateTemplate isn't recommended?

javaspringhibernate

提问by commit

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:

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

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

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

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?

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

采纳答案by JB Nizet

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 事务相关联的 Hibernate 会话,当SessionFactory.getCurrentSession()不存在时。由于它现在存在(并且很长一段时间内:即使在 hibernate3 包中也不鼓励使用 HibenateTemplate),因此没有理由使用这个 Spring 特定的类而不是SessionFactory.getCurrentSession()用于获取与当前 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:

如果你使用 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.)
}

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.

在上面的例子中,一个事务将在方法调用之前启动(如果尚未启动);Spring 会为事务创建一个会话,会话会在事务提交之前自动刷新,当方法返回时 Spring 会自动完成。