Issue
Is there a way for me to find out which Classes (i.e instance of which different types ) are cached in hibernate second level cache.
Solution
The second level cache doesn't cache instances of entities, it caches a "dehydrated" version of entities. This is well explained in this blog post:
The 2nd level cache
The hibernate cache does not store instances of an entity - instead Hibernate uses something called dehydrated state. A dehydrated state can be thought of as a deserialized entity where the dehydrated state is like an array of strings, integers etc and the id of the entity is the pointer to the dehydrated entity. Conceptually you can think of it as a Map which contains the id as key and an array as value. Or something like below for a cache region:
{ id -> { atribute1, attribute2, attribute3 } } { 1 -> { "a name", 20, null } } { 2 -> { "another name", 30, 4 } }
If the entity holds a collection of other entities then the other entity also needs to be cached. In this case it could look something like:
{ id -> { atribute1, attribute2, attribute3, Set{item1..n} } } { 1 -> { "a name", 20, null, {1,2,5} } } { 2 -> { "another name", 30, 4, {4,8} } }
Depending on the L2 cache provider you're using, you might get some console to monitor/browser the cache but, still, you won't see "instances".
Resources
- Hibernate Caches
- Hibernate: Truly Understanding the Second-Level and Query Caches
- Understanding Caching in Hibernate – Part Three : The Second Level Cache
Answered By - Pascal Thivent
Answer Checked By - David Marino (JavaFixing Volunteer)