JPA学习笔记(11)——使用二级缓存

Posted liguangsunls

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JPA学习笔记(11)——使用二级缓存相关的知识,希望对你有一定的参考价值。

一级缓存

查询两次id为1的user

User user1 = entityManager.find(User.class, 1);
User user2 = entityManager.find(User.class, 1);

结果发现仅仅调用了一次sql查询,由于使用了一级缓存

技术分享

假设查询一次后,关掉entityManager,再查询

User user1 = entityManager.find(User.class, 1);

entityManager.close();
entityManager = factory.createEntityManager();

User user2 = entityManager.find(User.class, 1);

发现查询了两次。由于entityManager关闭之后,缓存也就没有了。

技术分享

使用二级缓存

所谓的二级缓存,也就是能够跨entityManager的缓存,也就是说:就算你关闭了entityManager,缓存也依旧在。

在配置文件persistence.xml中配置

<!-- 二级缓存相关 -->
<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"/>

缓存须要下面jar包:

技术分享

在src下增加一个配置文件:ehcache.xml。这个文件直接拷贝来用即可了,不用理会里面的内容。有须要的时候再研究也不迟

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User‘s home directory
         user.dir - User‘s current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

启用二级缓存:

1.在实体类上加注解@Cacheable(true)

@Cacheable(true)
@Table(name="T_USER")
@Entity
public class User ...

2.在配置文件persistence.xml中配置二级缓存的策略

<!-- 
配置二级缓存的策略 
ALL:全部的实体类都被缓存
NONE:全部的实体类都不被缓存. 
ENABLE_SELECTIVE:标识 @Cacheable(true) 注解的实体类将被缓存
DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的全部实体类
UNSPECIFIED:默认值。JPA 产品默认值将被使用
-->
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

注意:这个配置要放在provider 节点和class 节点后面

再次运行

User user1 = entityManager.find(User.class, 1);

entityManager.close();
entityManager = factory.createEntityManager();

User user2 = entityManager.find(User.class, 1);

结果仅仅调用了一次sql查询语句,说明二级缓存 起作用了。

技术分享

以上是关于JPA学习笔记(11)——使用二级缓存的主要内容,如果未能解决你的问题,请参考以下文章

WildFly 中的 JPA 共享缓存/二级缓存

[原创]java WEB学习笔记93:Hibernate学习之路---Hibernate 缓存介绍,缓存级别,使用二级缓存的情况,二级缓存的架构集合缓存,二级缓存的并发策略,实现步骤,集合缓存,查询缓

mybatis学习笔记(13)-查询缓存之二级缓存

Mybatis 学习笔记 —一级缓存二级缓存逆向工程

Mybatis学习笔记:一级缓存二级缓存

禁用 JPA 二级缓存不起作用