如何为几个实体使用两种不同的Hibernate缓存策略

Uel*_*ter 6 java spring caching hibernate jpa

对于我的应用程序,我想为几个实体使用两种不同的hibernate缓存策略.因此(afaik,请纠正我,如果我错了)在实体上使用注释

@Cache(usage=ConditionalStrategy)
public class MyEntity{
...
}
Run Code Online (Sandbox Code Playgroud)

不会起作用,因为"ConditionalStrategy"必须是一个常量字段(为了与注释一起使用).

我已经了解了如何使用hibernate.cfg文件为每个实体配置缓存策略(请参阅https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html#performance-cache-mapping)但我想使用Spring LocalContainerEntityManagerFactoryBean的JPA属性直接设置它们,即

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

我如何设置JPA属性以复制基于注释的配置?这甚至可能吗?

对于那些面临同样问题的人来说更新:如果有人遇到同样的问题,也可以考虑使用Spring Cache(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html)抽象而不是hibernate注释(这是我最后所做的)

Vla*_*cea 4

首先,使用 a 是没有意义的,ConditionalStrategy因为实际的缓存提供者(例如 Ehcache)只支持四种典型的缓存策略:

Hibernate 还允许您设置默认缓存策略:

hibernate.cache.default_cache_concurrency_strategy=read-write
Run Code Online (Sandbox Code Playgroud)

您可以使用实体级注释或 Hibernate 特定的 XML 配置来覆盖它。

无论如何,您不能在运行时使用条件缓存策略,因为实体缓存策略仅在启动时构建一次SessionFactory