Replacement for removed HibernateDaoSupport.getSession() method in Spring 5.3 available?

Viewed 18

In Spring 4.3, the org.springframework.orm.hibernate3.support.HibernateDaoSupport.getSession() method allowed us to obtain a wrapped session that was managed by Spring. That means, we did not have to close the session at the end of the unit of work.

Unfortunately, in Spring 5.3 this method was removed. I could not find it's equivalent in org.springframework.orm.hibernate5.support.HibernateDaoSupport. Did I miss something?

We are currently upgrading from Spring 4.3 to 5.3 and we do not want to use Spring's transactionManager that would come with getSessionFactory().getCurrentSession(), because we would have to annotate every DAO + method call with @Repository and @Transactional and there are many places where that could break our application. Instead, we would like to replace our legacy calls for HibernateDaoSupport.getSession() with a Spring 5.3 equivalent. Is that possible somehow?

1 Answers

In the mean time, I have found an appropriate solution.

This code:

public List<?> executeDBQuery(final String queryString) {
   final Query query =  this.getSession().createSQLQuery(queryString);   
   return query.list();
}

can be replaced by

public List<?> executeDBQuery(final String queryString) {
   return (List) hibernateTemplate.execute((HibernateCallback) session -> session.createSQLQuery(queryString).list();
}

Using the HibernateTemplate.execute() wrapper-method, since .execute opens/closes the session, which is exactly what I was looking for.

Related