java - hibernate : Is it possible to manually add objects to second level cache?

标签 java hibernate caching jpa second-level-cache

在我的项目中,我想缓存几个对象而不是整个表。所以我的问题是,有没有我可以用来手动将对象添加到 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/

相关文章:

hibernate - Spring 数据修订存储库 : not returning onetomany when using getRevisions

javascript - 为什么 $http.get 返回 304 错误

java - 用于缓存的 Netflix Zuul 前置过滤器不适用于少量压缩响应

java - Weblogic: java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z

java - JFrame 在单独的类中,ActionListener 怎么样?

java - 我想在具有面板 ArrayList 的 ScrollPane 中使用 BoxLayout

Java Splash Argument 使用 Jar 中的文件

java - 如何使用 persistence.xml 创建 EntityManagerFactory 的实例?

hadoop - Spark 作为Mapreduce 的存储层

Java : improve the smoothness of a slow thread animation?