How I can disable the second-level cache of some certain entities in Hibernate without changing annotations

大兔子大兔子 提交于 2019-12-13 11:45:02

问题


I'm using Hibernate second level cache in my application, for certain business reason I can't change the entity annotation any more.

In my project, apart from changing the Database from Hibernate, there exist also other native SQL that do not go through Hibernate. Therefore, the Hibernate second-level cache data could be stale after database being updated from native SQL. That's why I want to disable the second-level cache for certain entities (programmatically or other way than changing annotation).

Thanks in advance!


回答1:


WARNING: As Jens Schauder noted, it is impossible to configure Ehcache to store 0 elements in memory by setting maxElementsInMemory="0" as it effectively causes opposite effect - sets unlimited size for the cache. This behaviour is not mentioned on the Hibernate Caching page but is documented on Cache Configuration page.

I have quickly reviewed the documentation and haven't found alternative approach yet. I am unable to delete this answer by myself. :-(

My original suggestion:

You can configure the implementation provider of second level cache to short TTL times and/or to store 0 entries of particular entity type.

E.g. if you are using the Ehcache, you can configure it in ehcache.xml:*

<cache
name="com.problematic.cache.EntityName"
maxElementsInMemory="0" <<== this should effectively disable caching for EntityName
overflowToDisk="false" <<== Do not overflow any entries to disk
/>

See Hibernate Caching in Ehcache documentation.




回答2:


In Terracotta 3.1 and above, you can enable/disable Hibernate 2nd Level Caches on a per region basis, both in the configuration (statically) and at runtime, using the Terracotta Developer Console.

You can also monitor in realtime statistics about the cache and Hibernate, for individual nodes in a cluster or cluster-wide.

Terracotta is open source. For more details, check out Terracotta for Hibernate.



来源:https://stackoverflow.com/questions/934133/how-i-can-disable-the-second-level-cache-of-some-certain-entities-in-hibernate-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!