Multiple Second Level Cache Settings With One Hibernate Mapping
-
22-03-2021 - |
Question
Supose that there multiple Java applications which share a common entity module (Entity classes + Hibernate XML mappings). Currently, the entities are not enabled for caching (no <cache.../>
elements within the mappings).
Most of the applications are largly concerned with editing single entities an thus it cannot relie on second level cache.
Now, a new application is implemented which
- Should use the same entity mappings
- but must use 2nd level and query cache.
How to configure the cache?
Several observations:
I cannot add
<cache.../>
elements to the mappings since this would break the other applications which do not configure such a cache and which are not under my influence:Second-level cache is not enabled for usage [hibernate.cache.use_second_level_cache | hibernate.cache.use_query_cache]
- I can't find a way to activate an entity for caching outside of its mapping. Setting up a cache region for an entity in
ehcache.xml
does not help - Even if I could change all the other applications and add
<cache.../>
to the entity mappings, it does not work to disable the cache by settinghibernate.cache.use_second_level_cache=false
although it is said so in http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html, table 3.5
Solution
It looks like you can use <class-cache>
elements to configure caching in hibernate.cfg.xml
rather than in entity mappings, see 3.8. XML configuration file.
I guess you can afford creating a custom hibernate.cfg.xml
that would use existing mappings, and if not, there are Configuration.setCacheConcurrencyStrategy()
methods that might help as well.