Filter through model or dao?
How shou开发者_如何学Gold one go about filtering a series of domain objects according to user-defined criteria? Should the filtering methods be in the model or should they be in the DAO?
If you want to use your model objects only (mainly) as data containers you should put the filter into the DAOs you are already using. It is a good practice to make sure, that the user defined criteria are database independent (so pass your own filter object instead of plain e.g. Hibernate Criteria. query by example may work great, too).
Then your DAO methods can look like this:
public interface BeanDao
{
List<Bean> findAllByFilter(BeanFilter filter);
}
The choice of whether to retrieve a greater number of objects and then filter or simply to retrieve the correct objects in the first place depends on the underlying data. Most applications will use a combination of the two.
The things I would consider are:
Network bandwidth & Memory requirements
If after filtering there are a small number of results but a significantly larger number of results before filtering then it could be a waste of bandwidth and memory resources to do the filtering in code.
Query speed
Filtering the results in the database can be more expensive than doing the logic in code - disk vs memory. Indexes are required to make it worthwhile.
Maintainability
Creating new queries can be time consuming. It will definitely mean writing some sql and revisiting various phases of testing. It may require modifying the db schema such as adding an index to speed up the query.
When solving this problem in Java it might be worth considering the visitor pattern. I often use two interfaces SingleMatcher and MultipleMatcher to filter a collection of objects. Implementations of these can be combined to create new user-defined criteria. Another advantage of this is that once you have a the matchers users may want to use you won't have to go back to testing to create new criteria.
精彩评论