Stack Exchange
Spring ehcache - Not able to retrieve value based on custom key
I am using KeyGenerator to generate custom key while caching a component.
Here is the cacheable method:
@CachePut(value = "cacheOne", keyGenerator = "keyGenerator")
    public CachedObject cacheMeta(final Object obj1,
            final Object obj2,
            final CachedObject cachedObject) {
        return cachedObject;
}
Here is KeyGenerator implementation:
public Object generate(Object o, Method m ,Object ... params){
StringBuilder s=new StringBuilder();
return s.append(params[0].hashCode()).append(params[1].hashCode());
}
While retrieving value from cache, i am generating key as : 
StringBuilder s= new StringBuilder();
s.append(obj1.hashCode().append(obj2.hashCode()));
Element elt=CacheManager.getInstance("cacheOne").get(s)
But it always returns null.

The problem is that you are using a StringBuilder as the cache key. StringBuilder has no equals or hashCode defined. So it relies on the ones defined on Object.
Which basically means that the get used to get the cache entry doesn't match the one putting the entry.
Using toString() to put
StringBuilder s = new StringBuilder();
return s.append(params[0].hashCode()).append(params[1].hashCode()).toString();

and get
StringBuilder s = new StringBuilder();
s.append("a".hashCode()).append("b".hashCode());
Cache.ValueWrapper wrapper = cache.get(s.toString());

solves it.
But I have to things to say.
First, using a StringBuilder here is useless because using String concatenation will let the compiler add a StringBuilder under the hood but be much nicer to read. So you could do
return params[0].hashCode() + "" + params[1].hashCode();

and
Cache.ValueWrapper wrapper = cache.get("a".hashCode() + "" + "b".hashCode());

which will work perfectly and have the same performance.
Then, relying on hashcodes to create a key is not safe. Hashcodes can have collisions. Even when appending two hashcodes. So you might mix entries on a given key.
