Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 608
Kewei Shang Avatar asked Jun 01 '09 09:06

Kewei Shang


1 Answers

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.

like image 167
3 revs Avatar answered Sep 19 '22 12:09

3 revs