•
<
shared-cache-mode
>
节点:若
JPA
实现支持二级缓存,该节点可以配置在当前的持久化单元中是否启用二级缓存,可配置如下值:
–
ALL
:所有的实体类都被缓存
–
NONE
:所有的实体类都不被缓存
.
–
ENABLE_SELECTIVE
:标识
@Cacheable(true
)
注解的实体类将被缓存
–
DISABLE_SELECTIVE
:缓存除标识
@Cacheable(false)
以外的所有实体类
–UNSPECIFIED:默认值,JPA产品默认值将被使用
配置persistence.xml
<!--
配置二级缓存的策略
ALL:所有的实体类都被缓存
NONE:所有的实体类都不被缓存.
ENABLE_SELECTIVE:标识 @Cacheable(true) 注解的实体类将被缓存
DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的所有实体类
UNSPECIFIED:默认值,JPA 产品默认值将被使用
-->
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<!-- 连接数据库的基本信息 -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="1230"/>
<!-- 配置 JPA 实现产品的基本属性. 配置 hibernate 的基本属性 -->
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<!-- 二级缓存相关 -->
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
</properties>
在实体类上使用@cache注解
jpa查询方法中
String jpql = "select u.name,u.email from User u";
List users = entityManager.createQuery(jpql).setHint(QueryHints.HINT_CACHEABLE, true).getResultList();
System.out.println(users);
即可调用二级缓存。