Wednesday, 21 November 2012

Generic Dao

When working with Spring and I Hibernate I often travel along the following loop:

1) Create an Entity Class (with jpa annotations)
2) Create Dao class (will extend some generic dao to inherit common functionality, like save, get)
3) Define a service interface to access the dao with an MVC controller (and to use proxy based method calling)
4) Create an implementation for the service

Now this setup creates quite a lot of unnecessary work. Say I add a method to a dao. I also have to
add a method to the service interface and service implementation so it can be called from the app code. This usually leads to the service layer being nothing more than a way to redirect calls to the dao. Furthermore most daos will just have a single custom method and inherit most of the methods from it's generic parent. The 3 tier architecture is useful for providing flexibility, but it creates too many shallow classes.

Heres a technique which has the flexibility of the 3 tier architecture, and also drastically reduces the number of shallow dao classes. The classes in this set up are:

1) The Db class (The Generic Dao )
2) DbCallback (An interface to to provide callback functionality (similar hibernate's callback), the current session will be passed as the first argument.

First the db class



Some examples, db is an instance of Db.class injected by spring

db.executeCallback() will call the execute method in Db.Callback interface, passing in an open session, allowing the class to use the session.

Move code that used to be in the dao to the service layer. Instead of having shalow service layers. The DAO (disc/db access object) pattern no longer applies, since hibernate is  an orm which handles that.

No comments:

Post a Comment