вівторок, 7 жовтня 2008 р.

Use criterias to enhance the search of your DAOs

I was reviewing the DZone today and found the blog entry who needs implementations? It is interesting approach but in my opinion it is nothing then just "unusual". I think that it will take same amount of time writing method and parameter annotation as it would take to write an actual implementation.

But let's postpone the discussion about it. I'd like to share my approach I used on several projects.

Here the common DAO interface:

public interface UserDAO extends GenericDAO {
...
}

GenericDAO has common methods like save, delete, update, etc.

In most cases you need some search methods and most developers are usually creating numerous of methods to perform all types of different search, like findByName , findByNameAndEmail, findByUsername etc. Also these methods are usually have "twins" methods for counting results.

Some smarter developers using "example" beans for searching. But you should be very careful because of the default values assigned to the bean properties.

I don't like both approaches, I like "Hibernate Criteria API" approach. But because it is very low level and because I do not wish to expose third-party API in my DAOs I need additional level of abstraction over it.

public interface SearchCriteria {
int count();
List find();
List find(int fromIdx, int maxCount);
T findUnique();
}

public interface UserSearchCriteria extends SearchCriteria{
UserSearchCriteria addUsernameRestriction(String username);
UserSearchCriteria addEMailRestriction(String email);
...
}


So your final code might look like this:

UserDAO userDAO = ...;
UserSearchCriteria criteria = userDAO.createCriteria();
criteria.addUsernameRestriction("vasya").addEMailRestriction("pupkin@gdeto.com");

//To get amount of results that criteria is able to find
int amount = criteria.count();

//To display results for page number "pageNum"
List users = criteria.find((pageNum - 1) * perPageCount, perPageCount);

I'm not showing the actual implementation since it very straightforward if you are using hibernate criteria API. You can actually use SQL/HQL if you like but it will be more complicated to join strings into final query.

You may also be able to "detach" your criterias so they can be stored in HTTP session rather then storing values and re-create your search over again on the next request. you are also free to add ordering and whatever you need to fine your search.

So who needs implementations?

I need!

0 коментарі: