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

时间:2015-07-30 14:47:02

标签: java spring hibernate jpa caching

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

等实体上使用注释
@Cache(usage=ConditionalStrategy)
public class MyEntity{
...
}

不能用作" 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);

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

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

1 个答案:

答案 0 :(得分:4)

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

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

hibernate.cache.default_cache_concurrency_strategy=read-write

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

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