18

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?

commit
  • 4,777
  • 15
  • 43
  • 70
  • See http://stackoverflow.com/questions/4067775/spring-hibernate-template-when-to-use-and-why/4067801#4067801 and http://stackoverflow.com/questions/5104765/hibernatedaosupport-is-not-recommended-why/5104965#5104965 – StormeHawke Aug 01 '13 at 19:31

1 Answers1

41

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • What about query case? Do I have to add @Transactional on query methods? – Yugang Zhou Aug 02 '13 at 01:19
  • Yes. Every Hibernate interaction should be done in a transaction. – JB Nizet Aug 02 '13 at 05:34
  • if we get session using sessionFactory.getCurrentSession(), should we need to close the session ( session.close() ) once the query is executed ? or it will automatically done by spring. – user1919581 Jan 19 '18 at 08:34
  • Does the documentation close the session? https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#orm-hibernate-straight. What do you conclude? – JB Nizet Jan 19 '18 at 08:37
  • @JB Nizet, checked that link, its not required to close it, will be taken care by spring transaction. Thank you. – user1919581 Jan 19 '18 at 11:29