Usability - Productivity - Business - The web - Singapore & Twins

Caching Lookup results in XPages

Nathan and John have shown before how a column value in an XPages view can contain the result from a lookup into another view (Notes or RDBMS). As you all know " With great powers ....". These lookups are executed once per row in the view. If there is a possibility, that the lookup key is repeating, it is a good idea to cache these values. Depending on your application this can be the one of the scopes: requestScope, viewScope, sessionScope or applicationScope. A very simple cache mechanism can look like this:
var myLookups ={  
    "getColor":function(color ,name){
        var fruit ;
        if(requestScope. fruit!=null){
            fruit = requestScope. fruit;
                fruit =new java. util. HashMap();
        if(fruit. containsKey(color )){
            var result = fruit. get(color );
            return result ;
        var lookResult =@DbLookup (@DbName (),"Fruits", color ,3);
        fruit. put(color ,lookResult );
        requestScope. fruit= fruit ;
        return@Trim (@Replace (lookResult ,name,""));
The function can be called with myLookups.getColor("red","Apple"); (the function returns all fruits of a given color except the current fruit handed over as the second parameter). If you have a lot of variables to cache a HashMap might not get the best result and you could consider using JCS. To test if it is working alter the function like this (Line 12+13):
  1. var myLookups ={  
  2.     "getColor":function(color ,name){
  3.         var fruit ;
  4.         if(requestScope. fruit!=null){
  5.             fruit = requestScope. fruit;
  6.         }else{
  7.                 fruit =new java. util. HashMap();
  8.         }
  10.         if(fruit. containsKey(color )){
  11.             var result = fruit. get(color );
  12.             fruit. put(color , result +" x");
  13.             return result +" x";
  14.         }
  16.         var lookResult =@DbLookup (@DbName (),"Fruits", color ,3);
  18.         fruit. put(color ,lookResult );
  19.         requestScope. fruit= fruit ;
  21.         return@Trim (@Replace (lookResult ,name,""));
  22.     }
  23. }
Every time the "Cache" is hit you will get one "x" more in the result. Once satisfied you can remove that test code.
As usual YMMV

Posted by on 25 January 2011 | Comments (2) | categories: XPages


  1. posted by Julian Buss on Tuesday 25 January 2011 AD:
    see also DbLookupArray and DbColumnArray functions in xpageswiki.com:
    { Link }
  2. posted by Terry Boyd on Sunday 30 January 2011 AD:
    Good stuff as usual Stephan!

    I find it a little easier/cleaner to use the following logic to setup the "fruit" variable...

    var fruit = (requestScope.fruit || new java.util.HashMap());

    Just wanted to add to an already excellent tip.