Search code examples
hibernatejpacachingjpa-2.0second-level-cache

Second Level Cache - Why not cache all entities?


In my experience, I have typically used the shared cache setting:

<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

My process is to then think about which entities are not expected to change often and those that would benefit from the cache, performance wise, and mark those as @Cacheable. My practice of using selective entity caching is a learned convention, but I don't fully understand this approach.

Why not cache all entities? When can caching all entities become a detriment? How can I better gauge this to make a more educated decision?


Solution

  • Some of reasons not to cache entities:

    1. When the entities are changed frequently (so you would end up invalidating/locking them in the cache and re-reading them anyway, but you pay an extra cost of cache maintenance which is not low since cache write operations would be frequent).
    2. If there are a large number of entity instances to cache and none of them is used more frequently than the others within a given period in time. Then you would basically put instances in cache and evict them soon afterwards to make room for new ones, without reading the cached instances frequently enough to make the cache maintenance costs pay off.
    3. If the entities can be changed without Hibernate being aware of that (from an external application or with direct JDBC for example).