开发者

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

开发者 https://www.devze.com 2023-03-12 13:02 出处:网络
I have a long-running EntityManager which I periodically clear().I have a read-write cache configured on one of my entities.

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 ther开发者_如何转开发e a way I can customise hibernate or ehcache to achieve cache hits within a single EntityManager?


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.


As the JavaDoc say: The timestamp says the Entity was created after the transaction started, so the transaction can't possibly see it (as per ACID).

So it seems that you have several transactions, say A and B. You start B, then A, then A creates instance X and then B tries to look up X -> cache miss since A isn't committed, yet (for example).

0

精彩评论

暂无评论...
验证码 换一张
取 消