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:

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,