Why is HibernateDaoSupport not recommended?
HibernateSpringHibernate Problem Overview
I've been doing some work with Hibernate 3.5 and Spring 3 recently, I'm fairly new with Hibernate and thought the HibernateDaoSupport
class in Spring made it nice and easy to use Hibernate with my domain classes.
However, while searching for an unrelated question I saw someone mention that the HibernateDaoSupport
is not the best way to use Spring and Hibernate. Can anyone shed any light on:
- Why is it not recommended?
- What is the best (or at least the accepted) way to integrate Hibernate and Spring?
Hibernate Solutions
Solution 1 - Hibernate
Using HibernateDaoSupport
/HibernateTemplate
is not recommended since it unnecessarily
ties your code to Spring classes.
Using these classes was inevitable with older versions of Hibernate in order to integrate support of Spring-managed transactions.
However, since Hibernate 3.0.1 you don't need it any more - you can write a code against a plain Hibernate API while using Spring-managed transactions. All you need is to configure Spring transaction support, inject SessionFactory
and call getCurrentSession()
on it when you need to work with session.
Another benefit of HibernateTemplate
is exception translation. Without HibernateTemplate
the same functionality can be achieved by using @Repository
annotation, as shown in Gareth Davis's answer.
See also:
Solution 2 - Hibernate
For my money there is nothing wrong with using HibernateDaoSupport
. It isn't deprecated in spring 3.0.
Can you provide the question number that you found, it maybe they where refering to a very specific use case.
The alternative is to use the @Repository
annotation. This will wire in the same exception translation (one of the big benefits of the HibernateTemplate
) and allow you to either use your own super class or just simply to avoid extending a third party framework class.
@Repository
public class YourFooDao {
@Resource
private SessionFactory sessionFactory;
private Foo get(long id){
return (Foo) sessionFactory.getCurrentSession().get(id);
}
}