在我的项目中,我想缓存几个对象而不是整个表。所以我的问题是,有没有我可以用来手动将对象添加到 hibernate 二级缓存的 API? (或者有没有办法为二级缓存指定表数据区域?)
最佳答案
您可以使用 @Cacheable(true) 进行注释您要缓存的实体
@Cacheable(true)
@Entity
public class Person { ... }
然后在您的 persistence.xml 配置文件中,您需要设置 shared-cache-mode
元素以使用 ENABLE_SELECTIVE
:
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
现在:
Caching is enabled for all entities for Cacheable(true) is specified. All other entities are not cached.
要指定区域,您可以使用 Hibernate 特定的 @Cache
注释:
@Cacheable(true)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="your-entity-region")
@Entity
public class Person { ... }
现在,您必须启用二级缓存:
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<property name="hibernate.cache.region.factory_class">ehcache</property>
要将实体添加到二级缓存,您只需要加载实体(它会自动缓存):
Person person = entityManager.find(Person.class, 1L);
关于java - hibernate : Is it possible to manually add objects to second level cache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541147/