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.

Problem:

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

Solution:


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 );

Caution: 

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
http://ytoh.wordpress.com/2008/07/17/ruby-like-collection-handling-in-verbose-java-collectionutils/


Comments

  1. We are using the Google Guava API which uses these kinds of functional idioms extensively.
    http://code.google.com/p/guava-libraries/wiki/FunctionalExplained

    It has really improved the code readability of our project!

    ReplyDelete
  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.

    ReplyDelete

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: