spring HibernateTemplate 与 HibernateDaoSupport 与 SessionFactory 注入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12971101/
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-09-08 05:26:39  来源:igfitidea点击:

HibernateTemplate vs HibernateDaoSupport vs SessionFactory Injection

springhibernate

提问by Arun Kumar

I have seen in lot of forums and still in confusion. We are starting a new project with Spring 3.1 & Hibernate 4 and need to decide which strategy to use for Hibernate with Spring:

我在很多论坛上看到过,仍然很困惑。我们正在使用 Spring 3.1 和 Hibernate 4 启动一个新项目,并且需要决定使用 Spring 的 Hibernate 使用哪种策略:

  1. Accessing Hibernate directly

    Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction();

  2. Using HibernateTemplate

    List bb = (List)hibernateTemplate.find("from Entity");

  3. Using HibernateDAOSupport classes

    List bb =(List)getHibernateTemplate().find("from Entity");

  1. 直接访问 Hibernate

    会话会话 = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction();

  2. 使用 HibernateTemplate

    List bb = (List)hibernateTemplate.find("from Entity");

  3. 使用 HibernateDAOSupport 类

    List bb =(List)getHibernateTemplate().find("from Entity");

Can you please help what should i use? I have read from CodeRanchand one another linkwhich tell that from Hibernate 3.xonwards we should inject SessionFactoryin our DAO Classes(using @Repository).

你能帮忙我应该用什么吗?我已经阅读了CodeRanch和另一个链接,它告诉我们从Hibernate 3.x开始我们应该注入SessionFactory我们的 DAO 类(使用@Repository)。

Can someone explain this in detail?

有人可以详细解释一下吗?

Regards,

问候,

Arun Kumar

阿伦·库马尔

回答by JB Nizet

Spring itself recommends not using HibernateTemplate anymore, in the javadocof the class. You can declare the session factory as a Spring beandirectly, inject it as any other Spring bean in your own components, and use the native Hibernate API directly (using sessionFactory.getCurrentSession()).

Spring 本身建议不要在类的 javadoc中使用 HibernateTemplate 。您可以直接将会话工厂声明为 Spring bean,将其作为任何其他 Spring bean 注入您自己的组件中,并直接使用本机 Hibernate API(使用sessionFactory.getCurrentSession())。

回答by duffymo

If you must use Hibernate, your best bet is to ignore Code Ranch (and SO) and follow the recommendation from Spring:

如果您必须使用 Hibernate,最好的办法是忽略 Code Ranch(和 SO)并遵循 Spring 的建议:

http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/

http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/

回答by KaviK

Now SessionFactory is recomended for Hibernate 4 for open/close connection automatically. So no need to use HibernateTemplate class.

现在 SessionFactory 被推荐用于 Hibernate 4 以自动打开/关闭连接。所以不需要使用 HibernateTemplate 类。