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:
The remaining operations on this HibernateTemplate are deprecated in the meantime and primarily exist as a migration helper for older Hibernate 3. x/4.
public abstract class HibernateDaoSupport extends DaoSupport. Convenient super class for Hibernate-based data access objects. Requires a SessionFactory to be set, providing a HibernateTemplate based on it to subclasses through the getHibernateTemplate() method.
getHibernateTemplate() Return the HibernateTemplate for this DAO, pre-initialized with the SessionFactory or set explicitly. protected Session. getSession() Obtain a Hibernate Session, either from the current transaction or a new one.
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:
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With