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

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

问题描述

我习惯于在hibernate 3中获取HibernateTemplate(),现在我正在转向Hibernate 4并在这里找不到以下类:

  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()方法自动管理的事务?

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



如果您使用Spring,那么您应该使用它的声明式事务管理,这样可以避免打开,承诺,关闭和冲洗。这些都是由Spring自动完成的:

  @Autowired 
private SessionFactory sessionFactory;

@Transactional
public void someMethod(){
//获取当前事务的会话:
Session session = sessionFactory.getCurrentSession();
//对会话进行处理(查询,合并,持续等)
}

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


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

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?

解决方案

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.

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.)
}

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天全站免登陆