Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use two different Hibernate caching strategies for a couple of entities

For my application, I'd like to use two different hibernate caching strategies for a couple of entities. Therefore (afaik, please correct me if I am wrong) using annotations on the entities like

@Cache(usage=ConditionalStrategy)
public class MyEntity{
...
}

will not work as "ConditionalStrategy" has to be a constant field (in order to be used with annotations).

I have seen how to configure the caching strategies per entity using the hibernate.cfg file (see https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html#performance-cache-mapping) but I would like to set them directly using the JPA properties of the Spring LocalContainerEntityManagerFactoryBean, i.e.

LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
Properties jpaProps = new Properties();
// what to put here to configure the caching strategies per entity?
jpaProps.put(..., ....) 
factory.setJpaProperties(jpaProbs);

How would I have to set the JPA properties to replicate the annotation based configuration? Is this even possible?

UPDATE for those facing the same problem: If someone runs into the same issues, also consider using the Spring Cache (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html) abstraction instead of the hibernate annotations (which is what I have done in the end)

like image 257
Ueli Hofstetter Avatar asked Jul 30 '15 14:07

Ueli Hofstetter


Video Answer


1 Answers

First of all, it makes no sense to use a ConditionalStrategy because the actual caching provider (e.g. Ehcache) only supports the four typical caching strategies:

  • read-only
  • nonstrict-read-write
  • read-write
  • transactional

Hibernate allows you to set a default caching strategy as well:

hibernate.cache.default_cache_concurrency_strategy=read-write

and you can override it using entity-level annotations or the Hibernate specific XML configurations.

Anyway, you can't use a conditional caching strategy at runtime because the entity cache policy is built only once when the SessionFactory is started.

like image 140
Vlad Mihalcea Avatar answered Oct 31 '22 15:10

Vlad Mihalcea