Why does hibernate/ehcache second level cache always miss within the same session?

Tags: , ,



I have a long-running EntityManager which I periodically clear(). I have a read-write cache configured on one of my entities.

I have done some investigation and I can see that the entity is present in the cache. I can even see a cache hit from net.sf.ehcache.Cache.searchInStoreWithStats(). However, ehcache will not return the entity if its timestamp is later than the timestamp when the session was created: see AbstractReadWriteEhcacheAccessStrategy.get(Object, long).

What is the reason for this behaviour? Is there a way I can customise hibernate or ehcache to achieve cache hits within a single EntityManager?

Answer

It looks like this is a property of a read-write cache: you can’t fetch an entity from the cache that was created in the same session.

A non-strict read-write cache doesn’t compare timestamps, so this does achieve a cache hit after the first load().

Even better, a transactional cache populates the cache after persist(), so the very first load() will result in a cache hit. Since my interaction with the databse is entirely within a single thread in a single JVM, I believe this is safe to use.



Source: stackoverflow