4

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:

  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");

Can you please help what should i use? I have read from CodeRanch and one another link which tell that from Hibernate 3.x onwards we should inject SessionFactory in our DAO Classes(using @Repository).

Can someone explain this in detail?

Regards,

Arun Kumar

Arun Kumar
  • 6,534
  • 13
  • 40
  • 67
  • Make sure that you really need Hibernate. It's not necessary to work with databases. Be sure that you know what the benefits and tradeoffs before you assume. – duffymo Oct 19 '12 at 09:21
  • Hibernate is already finalized for new Project. But need to know the best strategy from above. – Arun Kumar Oct 19 '12 at 09:31
  • 1
    Great question, there's so much overlap between the different technologies. – tylerwal Apr 22 '20 at 17:02

3 Answers3

10

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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

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

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

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

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

KaviK
  • 625
  • 9
  • 18