Hibernate != DAO

I made some wild and over-simple assertions last week hoping to provoke some response. I seem to have succeeded. One that caught Louis’s attention was a declaration that Hibernate was not a DAO. He challenged me to explain, so here it goes …

I suppose the first task is defining DAO. The Data Access Object pattern is a common pattern that arises from all of the different ways you might access data. Rather that expose the clients to JDBC, file IO, EJB entities, and Hibernate sessions, we create a simpler interface and hide the details. The abstraction I’ve seen most is composted of records (DTOs) with standard create/read/update/delete and query operations provided by the DAO layer.

So why does Hibernate not fit? To be simplistic, the Hibernate API is one of the many you would hide underneath the DAO interface. The premise of the DAO pattern is that you can find a common data access pattern, which usually requires a simpler model. But more specifically, there are real behaviour differences. For example:

public void daoUpdateStaff() {
        Staff staff = dao.getStaff(45);
        staff.setFirstName("Susan");
        dao.updateStaff(staff);
    }
    public void hibernateUpdateStaff() {
        Staff staff = (Staff) getSession().get(Staff.class, 45);
        staff.setFirstName("Susan");
    }

These two snippets do the same thing. But the Hibernate method doesn’t have an explicit update call. That is because the staff object is connected to the Hibernate session, and will be flushed back to disk on commit. Programmers expecting traditional DAO semantics will be very surprised by behaviour more like EJB Entities.

There are other related issues with object identity. Hibernate maintains a unique instance for a given session,

public void testIdentity() {
    	Staff staff0 = (Staff) getSession().get(Staff.class, 45);
    	Staff staff1 = (Staff) getSession().get(Staff.class, 45);
    	assertSame(staff0, staff1);
    }

while DAOs usually just return new records. This can get very awkward when merging new data in from remote clients.

I like Hibernate. I like the connected/persistent objects. I think using Hibernate raw is an appealing option in web apps. I just want people to know what they are getting into.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply