[英]Hibernate : Is it possible to manually add objects to second level cache?
In my project I want to cache few objects but not whole table. 在我的项目中,我想缓存几个对象,而不是整个表。 So my problem is, is there a API that i could use to manually add objects to hibernate second level cache ?
所以我的问题是,是否有可以用来手动添加对象以休眠第二级缓存的API? ( Or is there a way to specify table data region for second level cache ? )
(或者是否可以为二级缓存指定表数据区域?)
You can annotate with @Cacheable(true) the entities you want to cache 您可以使用@Cacheable(true)注释要缓存的实体
@Cacheable(true)
@Entity
public class Person { ... }
and then in your persistence.xml configuration file, you need to set the shared-cache-mode
element to use ENABLE_SELECTIVE
: 然后在persistence.xml配置文件中,需要将
shared-cache-mode
元素设置为使用ENABLE_SELECTIVE
:
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
so now: 所以现在:
Caching is enabled for all entities for Cacheable(true) is specified.
为所有实体启用了缓存,并为Cacheable(true)指定了缓存。 All other entities are not cached.
所有其他实体均未缓存。
To specify regions, you can use the Hibernate specific @Cache
annotation: 要指定区域,可以使用特定于Hibernate的
@Cache
注释:
@Cacheable(true)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="your-entity-region")
@Entity
public class Person { ... }
Now, you have to enable the 2nd-level cache: 现在,您必须启用二级缓存:
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<property name="hibernate.cache.region.factory_class">ehcache</property>
To add entities to the 2nd level cache, you just need to just load the entity (and it will be cached automatically): 要将实体添加到第二级缓存中,您只需加载实体(实体将被自动缓存):
Person person = entityManager.find(Person.class, 1L);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.