Abhijat M

Abhijat M

Monday, 10 September 2012

Predicates Java Pattern to save Database Queries

The apache commons CollectionUtils has a collection of very interesting methods to allow using Ruby style collection filtering, rejecting,collecting injecting ...

I found the select method quite useful to avoid multiple DB Queries with a DB similar predicate and syntactically clean.


I wish to append a List/Collection to my Bean based on some predicate (orgId="mcool").


Use of Predicates:

Basic Example:

BeanPropertyValueEqualsPredicate  predicate = new BeanPropertyValueEqualsPredicate("orgId", value);

 BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate("orgId", value);  
 Collection<Organisation> organisationCool = CollectionUtils.select(allOrgansations, predicate);  
allOrganisations above was fetched with a single sql select.

bean.setOrganisationsList(organisationCool );


Needless to say but typically small datasets and only for cases where in memory selection is beneficial.

More about the Ruby style collection handling in this blog here