- Let your concrete DAO class extend
HibernateDaoSupport. This base class has to be configured with a
SessionFactoryand gives access to Hibernate Sessions and a
- Directly injecting a
HibernateTemplateinto your DAO class. You don't have to extend any framework class. The
HibernateTemplategives access to many general purpose dao methods. This is o.k. for many cases but accessing the hibernate session directly from the HibernateTemplate is verbose. You have to pass anonymous callbacks to get access to the session.
On the other side the
HibernateTemplateis handy when it comes to automatic handling of the hibernate session management (e.g. binding the session to the current Transaction) but as you'll see this is no longer needed in Hibernate 3. It also converts any Hibernate or SQL related Exception into a corresponding
DataAccessException, which is very helpful.
- Directly injecting the Hibernate
SessionFactoryinto your DAO class. Your DAO won't have dependancies on any class from the Spring Framework. Since Hibernate 3 is capable of binding the Session to a preset Context (e.g. Thread or Transaction) the HibernateTemplate is no longer needed.
Session#getCurrentSession()(see Hibernate documentation for details).
As you can read in the Javadoc of HibernateTemplate the Spring Team confirms this:
NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate3 style of coding data access objects instead, based onYou may ask how you can get DataAccessExceptions with this variant? This is quite simple: just annotate your DAOs with
@Repositoryand include this Spring Bean into you ApplicationContext: