EhCache key type

Matthieu Napoli picture Matthieu Napoli · May 6, 2011 · Viewed 8.8k times · Source

In EhCache, when adding an element to the cache :

cache.put(new Element("key1", "value1"));

// Element constructors :
Element(Object key, Object value)

I see I can give an Object as the key index.

How can I use this to have a "complex" key, composed of multiple int : (userId,siteId,...) instead of a string as an index ?

Thanks

Answer

Bozho picture Bozho · May 6, 2011

Wrap it in a new class:

public class CacheKey implements Serializable {
    private int userId;
    private int siteId;
    //override hashCode() and equals(..) using all the fields (use your IDE)
}

And then (assuming you have defined the appropriate constructor):

cache.put(new Element(new CacheKey(userId, siteId), value);

For simple cases you can use string concatenation:

cache.put(new Element(userId + ":" + siteId, value));