Spring and Hibernate, Simplify the DAO layer


When developing web applications, many people create their data access layer using two basic design patterns(design pattern meaning an informal description, not to be confused with the gang of four). The first is to put the responsibility on the DAO class of acquiring the data source. Approaches may vary from coding this in a super class to externalizing it in a specialized delegate class. The bottom line is that the DAO cannot provide value to your app without obtaining a data source directly(e.g. JNDI) or via a delegate class. One of the major limiting factors here is that your DAO classes are not easily testable outside of the container. An arguable better implementation would be to parameterize the data source. This allows the unit test to acquire the data source independent of the DAO class and pass it in upon execution. This has an upside for the DAO class since it can focus on it's primary responsibility of providing data. This also makes the DAO class testable outside the container since the unit test would pass it in. It's a win, win situation right? Well not exactly! The downside is that now client modules, unit tests in this case, need to know how to obtain a data source. This is a grave injustice placed on the client code developers. After all, part of the reason that we have the DAO layer is to simplify data access. Pick your poison: Testable and inflexible or flexible but difficult to test.

To make things worse, what if you want to swap out your JDBC DAO classes for ones that use a persistence framework like Hibernate. Hibernate catches my eye because I immensely dislike writing gobs of SQL. For a Java programmer, Hibernate offers a much more natural way of persisting objects. Instead of writing JDBC code, hibernate allows me to deal with POJO's and persist them for me. The bulk of my work lies in maintaing OR Mapping files. With hibernate, developers working outside the data access layer will not know which classes are persisted and which are not since the POJO's do not extend or implement anything. So lets use hibernate in our application them. Unfortunately for us, our make believe application has DataSource's floating around in method signatures. Since hibernate uses a SessionFactory object instead of a data source, mass code changes will need to be made to make the transition. Obviously Hibernate knows about data sources under the covers but client code is not aware of that. For those of you thinking of a "find and replace" engineering solution, I hope I never get the opportunity to work with you :) The find and replace approach is similar to loosening a rusty bolt with a pair of pliers. It might work once, maybe twice, but over time your bolt's integrity will be compromised and in need of a replacement. The same is true for your code. It will start to deteriorate over time. I've seen this over and over and over again! Heck I may have even participated in this kind of macro programming in years past. What are the options now?

So far I have preached that working with Hibernate is easier and more enjoyable than working with JDBC directly. This is a personal opinion but one that I know many developers share. An even better approach is to use the Spring Framework with Hibernate. Bringing Spring into the mix will allow you to reduce the amount of plumbing code required for hibernate by a factor of 50% or more. In Spring Live, Matt Raible claims that this code reduction is in the neighborhood of 75%. I tend to agree with Matt and I have created a sample application to make my case. My application contains two unit tests(one DAO using just hibernate and the other using spring and hibernate) that create a 3 field record in a MySQL database(loosely based on the myusers app from spring live).

First both DAO classes implement the MyRecordDAO interface.

   1:package com.shoesobjects.dao;
   2:
   3:import com.shoesobjects.MyRecord;
   4:
   5:import java.util.List;
   6:
   7:public interface MyRecordDAO {
   8:    public MyRecord getRecord(Long id);
   9:
  10:    public List getRecords();
  11:
  12:    public void saveRecord(MyRecord record);
  13:
  14:    public void removeRecord(Long id);
  15:}

Here is the data access object using just hibernate. Not to bad but lots of cookie cutter try/catch blocks and redundant opening/closing of sessions. Notice it is 114 lines of code and would be even larger if I handled exceptions properly like any good programmer would.

   1:package com.shoesobjects.dao;
   2:
   3:import com.shoesobjects.MyRecord;
   4:import net.sf.hibernate.*;
   5:import net.sf.hibernate.cfg.Configuration;
   6:
   7:import java.util.List;
   8:
   9:public class MyRecordDAOHibernate implements MyRecordDAO {
  10:    private static SessionFactory sessionFactory = null;
  11:
  12:    public MyRecordDAOHibernate() {
  13:        Configuration cfg = null;
  14:        try {
  15:            cfg = new Configuration().addClass(MyRecord.class);
  16:        } catch (MappingException e) {
  17:            e.printStackTrace();
  18:        }
  19:
  20:        try {
  21:            sessionFactory = cfg.buildSessionFactory();
  22:        } catch (HibernateException e) {
  23:            e.printStackTrace();
  24:        }
  25:    }
  26:
  27:    private Session getSession() {
  28:        Session session = null;
  29:        try {
  30:            session = sessionFactory.openSession();
  31:        } catch (HibernateException e) {
  32:            e.printStackTrace();
  33:        }
  34:        return session;
  35:    }
  36:
  37:    public MyRecord getRecord(Long id) {
  38:        Session session = this.getSession();
  39:        MyRecord record = null;
  40:        try {
  41:            record = (MyRecord) session.load(MyRecord.class, id);
  42:        } catch (HibernateException e) {
  43:            e.printStackTrace();
  44:        } finally {
  45:            if (session != null) {
  46:                try {
  47:                    session.close();
  48:                } catch (HibernateException e) {
  49:                    e.printStackTrace();
  50:                }
  51:            }
  52:        }
  53:
  54:        return record;
  55:    }
  56:
  57:    public List getRecords() {
  58:        Session session = this.getSession();
  59:        List list = null;
  60:        try {
  61:            Query query = session.createQuery("select myrecord from com.shoesobjects.MyRecord");
  62:            list = query.list();
  63:        } catch (HibernateException e) {
  64:            e.printStackTrace();
  65:        } finally {
  66:            if (session != null) {
  67:                try {
  68:                    session.close();
  69:                } catch (HibernateException e) {
  70:                    e.printStackTrace();
  71:                }
  72:            }
  73:        }
  74:
  75:        return list;
  76:    }
  77:
  78:    public void saveRecord(MyRecord record) {
  79:        Session session = this.getSession();
  80:        try {
  81:            session.saveOrUpdate(record);
  82:            session.flush();
  83:        } catch (HibernateException e) {
  84:            e.printStackTrace();
  85:        } finally {
  86:            if (session != null) {
  87:                try {
  88:                    session.close();
  89:                } catch (HibernateException e) {
  90:                    e.printStackTrace();
  91:                }
  92:            }
  93:        }
  94:    }
  95:
  96:    public void removeRecord(Long id) {
  97:        Session session = this.getSession();
  98:        try {
  99:            MyRecord record = (MyRecord) session.load(MyRecord.class, id);
 100:            session.delete(record);
 101:            session.flush();
 102:        } catch (HibernateException e) {
 103:            e.printStackTrace();
 104:        } finally {
 105:            if (session != null) {
 106:                try {
 107:                    session.close();
 108:                } catch (HibernateException e) {
 109:                    e.printStackTrace();
 110:                }
 111:            }
 112:        }
 113:    }
 114:}

Hibernate uses a properties file or xml file for it's configuration information(datasource url, username, password, database dialect, etc). For simplicity, I'm listing only the necessary information.

   1:#hibernate.properties
   2:#only used for MyRecordDAOHibernateTest
   3:hibernate.connection.url = jdbc:mysql://localhost:3306/myrecord
   4:hibernate.connection.username = myrecord
   5:hibernate.connection.password = myrecord
   6:hibernate.dialect = net.sf.hibernate.dialect.MySQLDialect
   7:hibernate.connection.driver_class = org.gjt.mm.mysql.Driver
   8:hibernate.connection.driver_class = com.mysql.jdbc.Driver
   9:hibernate.hbm2ddl.auto = update

The unit test to exercise this DAO class is listed below. It is a pretty straight forward JUnit test. The only thing that might look out of the ordinary is that we are instantiating the MyRecordDAOHibernate() class directly. In practice, it would be beneficial to hide this behind a Factory. Then you could more easily allow for alternate implementations.

   1:package com.shoesobjects;
   2:
   3:import com.shoesobjects.dao.MyRecordDAO;
   4:import com.shoesobjects.dao.MyRecordDAOHibernate;
   5:import junit.framework.Assert;
   6:import junit.framework.TestCase;
   7:
   8:public class MyRecordDAOHibernateTest extends TestCase {
   9:        private MyRecord record = null;
  10:        private MyRecordDAO dao = null;
  11:
  12:    protected void setUp() throws Exception {
  13:        super.setUp();
  14:        dao = new MyRecordDAOHibernate();
  15:    }
  16:
  17:    protected void tearDown() throws Exception {
  18:        super.tearDown();
  19:        dao = null;
  20:    }
  21:
  22:    public void testSaveRecord() throws Exception {
  23:        record = new MyRecord();
  24:        record.setFirstName("Gavin");
  25:        record.setLastName("King");
  26:        dao.saveRecord(record);
  27:        Assert.assertNotNull("primary key assigned", record.getId());
  28:    }
  29:}

The version using Hibernate and Spring has a much cleaner implementation thanks to Springs. Notice this version doesn't have to deal with creating the SessionFactory or dealing with opening/closing sessions. The Spring Framework takes care of this under the covers for you. All you have to do is add the SessionFactory as a needed dependency in Spring's applicationContext.xml file. Notice this class is only 26 lines of code. Look at how clear and concise this version is.

   1:package com.shoesobjects.dao;
   2:
   3:import com.shoesobjects.MyRecord;
   4:import org.springframework.orm.hibernate.support.HibernateDaoSupport;
   5:
   6:import java.util.List;
   7:
   8:public class MyRecordDAOHibernateWithSpring extends HibernateDaoSupport implements MyRecordDAO {
   9:
  10:    public MyRecord getRecord(Long id) {
  11:        return (MyRecord) getHibernateTemplate().get(MyRecord.class, id);
  12:    }
  13:
  14:    public List getRecords() {
  15:        return getHibernateTemplate().find("from MyRecord");
  16:    }
  17:
  18:    public void saveRecord(MyRecord record) {
  19:        getHibernateTemplate().saveOrUpdate(record);
  20:    }
  21:
  22:    public void removeRecord(Long id) {
  23:        Object record = getHibernateTemplate().load(MyRecord.class, id);
  24:        getHibernateTemplate().delete(record);
  25:    }
  26:}

The applicationContext.xml file contains all the information for Spring's Bean Factory to instantiate the necessary class es and wire the dependencies. Notice the bean with an id of myRecordDAO, it has a reference to the bean sessionFactory which is also defined in this config file.

   1:<?xml version="1.0" encoding="UTF-8"?>
   2:<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
   3:    "http://www.springframework.org/dtd/spring-beans.dtd">
   4:
   5:<beans>
   6:<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   7:        <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
   8:        <property name="url"><value>jdbc:mysql://localhost:3306/myrecord</value></property>
   9:        <property name="username"><value>myrecord</value></property>
  10:        <property name="password"><value>myrecord</value></property>
  11:    </bean>
  12:
  13:    <!-- Hibernate SessionFactory -->
  14:    <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
  15:        <property name="dataSource"><ref local="dataSource"/></property>
  16:        <property name="mappingResources">
  17:            <list>
  18:                <value>MyRecord.hbm.xml</value>
  19:            </list>
  20:        </property>
  21:        <property name="hibernateProperties">
  22:        <props>
  23:            <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
  24:            <prop key="hibernate.hbm2ddl.auto">update</prop>
  25:        </props>
  26:        </property>
  27:    </bean>
  28:
  29:    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
  30:    <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
  31:        <property name="sessionFactory"><ref local="sessionFactory"/></property>
  32:    </bean>
  33:
  34:    <bean id="myRecordDAO" class="com.shoesobjects.dao.MyRecordDAOHibernateWithSpring">
  35:        <property name="sessionFactory"><ref local="sessionFactory"/></property>
  36:    </bean>
  37:</beans>

Here is the JUnit test for Hibernate+Spring implementation of the data access object. Notice it is just as straight forward as the last unit test but has one noticeable advantage. Look at line 22 where we instantiate the data access object. No concrete implementation is listed, only the interface. The concrete class is instantiated by Spring's BeanFactory behind the scenes allowing us to swap out the implementation by editing the applicationContext.xml descriptor. This flexibility allows our unit test to easily be modified to use a mock implementation without using command line parameters to the JVC or making code changes.

   1:package com.shoesobjects;
   2:
   3:import com.shoesobjects.dao.MyRecordDAO;
   4:import junit.framework.Assert;
   5:import junit.framework.TestCase;
   6:import org.springframework.context.ApplicationContext;
   7:import org.springframework.context.support.ClassPathXmlApplicationContext;
   8:
   9:public class MyRecordDAOHibernateWithSpringTest extends TestCase {
  10:    private ApplicationContext ctx = null;
  11:    private MyRecord record = null;
  12:    private MyRecordDAO dao = null;
  13:
  14:    public MyRecordDAOHibernateWithSpringTest() {
  15:        // Should put in a parent class that extends TestCase
  16:        String[] paths = {"applicationContext.xml"};
  17:        ctx = new ClassPathXmlApplicationContext(paths);
  18:    }
  19:
  20:    protected void setUp() throws Exception {
  21:        super.setUp();
  22:        dao = (MyRecordDAO) ctx.getBean("myRecordDAO");
  23:    }
  24:
  25:    protected void tearDown() throws Exception {
  26:        super.tearDown();
  27:        dao = null;
  28:    }
  29:
  30:    public void testSaveRecord() throws Exception {
  31:        record = new MyRecord();
  32:        record.setFirstName("Rod");
  33:        record.setLastName("Johnson");
  34:        dao.saveRecord(record);
  35:        Assert.assertNotNull("primary key assigned", record.getId());
  36:    }
  37:
  38:}

In order to run this example, the following steps are required.
1) Install MySQL, login as root
2) Create a database called myrecord
   create database myrecord;
3) Create a database user called myrecord with a password of myrecord.
   grant all privileges on myrecord.* to myrecord@localhost identified by 'myrecord' with grant option;
4) Run the unit test's. The database table will be created upon running the test due to the following line in applicationContext.xml
    <prop key="hibernate.hbm2ddl.auto">update</prop>
3) Run the unit tests

IntelliJ IDEA project files are included in the archive. Also, all required jar files are in the lib directory so you will not have to download anything else.

Download the sample app here.