Issue
I'm using ehcache as hibernate l2 cache in Java application. I want a way that I can customize the cache key, so in the future I translate the object ID to the cached key and evict it.
Is there a way to customize the key stored in the cache?
Solution
You can customize the cache keys by providing a custom org.hibernate.cache.spi.CacheKeysFactory
implementation, but to do that you need to register a custom org.hibernate.cache.spi.CacheImplementor
service, possibly extending org.hibernate.cache.internal.EnabledCaching
, or a custom org.hibernate.cache.spi.RegionFactory
service, possibly extending org.hibernate.cache.jcache.internal.JCacheRegionFactory
.
It's very cumbersome, but you can do it if you really want. What you can easily do though, is create the cache key by object id just like Hibernate does. Then you should be able to evict entries manually as well.
For entities, you can determine EntityDataAccess
through EntityPersister#getCacheAccessStrategy()
and for collections, you can determine CollectionDataAccess
through CollectionPersister#getCacheAccessStrategy()
. These two types offer a method called generateCacheKey
which is responsible for creating the cache key, which delegates to CacheKeysFactory
. The nice thing about these types is, that they also have the method evict
, so you don't have to care about the name mangling that Hibernate might do with cache names.
Answered By - Christian Beikov
Answer Checked By - Katrina (JavaFixing Volunteer)