javaspringehcache

Spring + Ehcache : How to cache find all result


I am using Spring + Ehcache for my caching layer. (via proxy)

I am wondering if you can cache both "findAll" result and "findById" result on the same cache and then CacheEvict the specific item and the "findAll" result (leaving the rest of the item untouched) and on the update and load it back to cache when "findById" again?

(or another way is to keep findAll and findById in 2 caches and when update CacheEvict allEntries for the findAll cache and the particular item on findById cache)

is this possible?


Solution

  • I will explain how with its second level and query cache work to give you a general idea. First of all Hibernate caches all single entities (e.g. retrieved by findById type of operations) in so-called second level cache.

    If you retrieve all entities using findAll it puts primary keys of all entities in query cache (under one key) and all concrete entities in second level cache. When you call findAll again, it first retrieves all primary keys from query cache and then all entities from second level cache (or from database).

    Invalidation is rather simple: INSERT and DELETE operations should invalidate the whole findAll query cache, while UPDATEs are transparent.

    This should guide you how can you implement this in your solution. This is possible in Spring, but you might need to code a little bit, especially the part mapping from query cache to second level cache.