Five ‘s Weblog

October 14, 2007

Spring DAO!

Filed under: Five's thought — by powerdream5 @ 1:02 am
Tags: , , ,

      Yesterday, I published an article about applying DAO pattern to encapsulate the persistent layer based on Hibernate framework. At the end of that artcile, I figured that we can use spring framework to make an advance to the exaple. In fact, Spring framework also adopts DAO pattern, however, which is different from the original DAO. In order to distinguish them, I want to call them spring DAO and original DAO respectively.

      I found an article in the internet which describes the differences between Spring DAO and original DAO in detail. I do not want to do some repetive work to explain the reason why Spring DAO is better than the other one. But I would like to answer the following two questions with you guys.


what is DAO template and what is DAO callback in spring framework?
The biggest differences between Spring DAO and original DAO is that Spring DAO is combinded with template method pattern. Because in the process of interactiving with the database, some steps ares invariable, for example, creating the connection and start the transaction. The original DAO does such things over and over again in each mehtod of the data access object. Fortunately, Spring DAO uses the template method pattern to solve this problem. Therefore, the invariable steps and variable steps are separated and encapsulated. So DAO template is the part which contains the invariable steps, and DAO callback is the part which contains the variable steps.

What is HibernateTemplate and What is HibernateDaoSupport?
Spring framework provides template class for Hibernate framework, which helps release the programmer from writing some repetive codes. This template class is called HibernateTemplate. However, sometimes some programer use HibernateTemplate, but some programers use HibernateDaoSupport. What are the differences between them? After reading the code of the class of HibernateDaoSupport, it is easy for us to answer this quesiton.

public abstract class HibernateDaoSupport extends DaoSupport{
      private HibernateTemplate hibernateTemplate;
      public final void setSessionFactory(SessionFactory sessionFactory){
             this.hibernateTemplate = CreateHibernateTemplate(sessionFactory);
    protected HibernateTemplate createHibernateTemplate(
           SessionFactory sessionFactory);{
           return new HibernateTemplate(sessionFactory);
    public final HibernateTemplate getHibernateTemplate(){
          return this.hibernateTemplate;

        It is obvious that HibernateDaoSupport encapsulates HibernateTemplate. In other words, HibernateDaoSupport seems more convenient than HibernateTemplate. We can make our DAO class extends HibernateDaoSupport instead of injecting the instance of HibernateTemplate to each DAO class.


Blog at