Skip to main content

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 =, 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


  1. We are using the Google Guava API which uses these kinds of functional idioms extensively.

    It has really improved the code readability of our project!

  2. +1 for guava too, but...
    Guava authors theirselves warn off overusage of functional idioms.
    In current state of Java one can either write anonymous class (which is lengthy and bad readable) or access field from by reflection using given String (which is impractical for refactoring). The Funcito library approach seems like interesting trade-off, however I haven't tried it yet.


Post a Comment

Popular posts from this blog

ActionController::Live rails 4 Nginx passenger and redis

This is the most common setup for rails applications and most straightforward solution for SSE aka server side events.

In order to get SSE to work using redis we just use Ajax to respond to publish events based on json fields being present but you can even send a pure data payload: