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:
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
var myLookups = {
"getColor" : function (color , name ) {
var fruit ;
if (requestScope. fruit != null ) {
fruit = requestScope. fruit ;
} else {
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 "getColor" : function (color , name ) {
var fruit ;
if (requestScope. fruit != null ) {
fruit = requestScope. fruit ;
} else {
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 , "" ) ) ;
}
}
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):-
var myLookups = {
-
"getColor" : function (color , name ) {
-
var fruit ;
-
if (requestScope. fruit != null ) {
-
fruit = requestScope. fruit ;
-
} else {
-
fruit = new java. util. HashMap ( ) ;
-
}
-
-
if (fruit. containsKey (color ) ) {
-
var result = fruit. get (color ) ;
-
fruit. put (color , result + " x" ) ;
-
return result + " x" ;
-
}
-
-
var lookResult = @DbLookup ( @DbName ( ) , "Fruits" , color , 3 ) ;
-
-
fruit. put (color ,lookResult ) ;
-
requestScope. fruit = fruit ;
-
-
return @Trim ( @Replace (lookResult , name , "" ) ) ;
-
}
-
}
As usual YMMV
Posted by Stephan H Wissel on 25 January 2011 | Comments (2) | categories: XPages