Hi Everyone,

As we all know AppFuse has a fantastic implementation of the DAO design
pattern.

However as I have been using AppFuse over the past 9 or so months I have
realized that the vast majority of the CRUD code I'm writing in the DAOs is
for the *reading*; retrieving objects by a combination of properties (e.g.,
show me all orders between dates X and Y with a status of Open in region Z).


Rarely do my pojos require any special code to create, update or delete -
usually that's either handled by ORM (hibernate in my case) or upstream in
the business logic somewhere.

After finding that I have quite a few DAOs (and service beans, and entries
in configuration files, etc.) I never used, I've started doing things a
little differently. Wherever possible, I use the generic DAO. To the base
DAO I've added a findByCriteria method that is simply a wrapper exposing the
Spring HibernateTemplate's findByCriteria method.

Then for each pojo I'll need to be able to query for in interesting ways
(interesting meaning beyond findByExample or ID), I create a filter whose
only job is to accept parameters and return a criteria object I can pass to
the generic DAO.

So using the example above, I'd write a OrderFilter that accepts a fromDate,
toDate, status, region. If any of those values are null they're ignored. If
they're not null they're added to the criteria. Any logic for preventing
screwy results (e.g., fromDate can't be after toDate) goes in the filter
class. OrderFilter has a getDetachedCriteria method that returns a hibernate
DetachedCriteria object for passing to the DAO.

The plus side is I have a lot fewer DAOs and service beans to
write/test/maintain. The downside is that I instead have new filter objects
to write/test/maintain. Plus the way I've implemented it is certainly
Hibernate-specific - I don't know if something like this would be possible
in Ibatis (you could certainly implement it in plain ol' jdbc).

Being naturally lazy, it's nice to know I'm only writing a DAO when it's
absolutely required, and I'm only writing filters on objects when absolutely
required (i.e., can't be found by ID or example).

Anyone have any thoughts on a design pattern like this? (Which we shall
nickname One DAO to Rule Them All.)

Jason

Reply via email to