JPA Learning - Lesson 13, Using L2 Cache

L1 cache

The first-level cache is a session-level cache. In JPA, an entityManager corresponds to a session, and a session corresponds to a cache.

Query twice the user whose id is 1

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

It turned out that the sql query was called only once, because the first-level cache was used. When the first find, the queried data was put into the cache, and the second time it was searched, it would go to the cache first. Use without re-querying.
write picture description here

If after querying once, turn off entityManager and query again

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

It was found that the query was performed twice, because after the entityManager was closed, its corresponding cache was gone.
Then restart an entityManager, which is not the same as the previous one.
write picture description here

Configure L2 cache

If the first level cache is a local cache associated with the session level, then the second level cache is the global cache.
It can be cached across entityManagers, that is to say: even if you close the entityManager, the cache is still there.

Configured in the configuration file applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置数据源 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <!-- 配置其他属性(省略) -->
    </bean>

    <!-- 配置 JPA 的 EntityManagerFactory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
        </property>
        <property name="packagesToScan" value="com.ssj.domain"></property>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <!-- 指定自动生成数据表的策略 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 执行操作时是否在控制台打印SQL -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 是否对SQL进行格式化 -->
                <prop key="hibernate.format_sql">true</prop>
                <!-- 方言 -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
                <!-- 开启二级缓存 ehcache -->
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
                </prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
            </props>
        </property>
        <!-- 配置二级缓存的策略
            ALL:所有的实体类都被缓存 
            NONE:所有的实体类都不被缓存. 
            ENABLE_SELECTIVE:标识 @Cacheable(true)注解的实体类将被缓存 
            DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的所有实体类 UNSPECIFIED:
            默认值,JPA 
            产品默认值将被使用 -->
        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"></property>

    </bean>
</beans>

Note: There are two places that need to be configured, one is to enable the second-level cache, and the other is to configure the cache policy.

Using the second level cache requires adding the following dependencies:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>${hibernate.version}</version>
</dependency>

In fact, there is also the jar package of ehcache-core, but when using hibernate-ehcache to integrate the jar package, the jar package of ehcache-core will be used, which is automatically added when this dependency is introduced.

Add a configuration file to the resources folder: ehcache.xml, just copy this file and use it directly, don't pay attention to the content inside, it's not too late to study it when you need it

<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>

Use second level cache

The first method
1. Annotate the entity class with @Cacheable(true)

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

2. Configure the second-level cache strategy in the configuration file applicationContext.xml
This has been configured above

<!-- 配置二级缓存的策略
    ALL:所有的实体类都被缓存 
    NONE:所有的实体类都不被缓存. 
    ENABLE_SELECTIVE:标识 @Cacheable(true)注解的实体类将被缓存 
    DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的所有实体类 UNSPECIFIED:
    默认值,JPA 
    产品默认值将被使用 -->
<property name="sharedCacheMode" value="ENABLE_SELECTIVE"></property>

execute again

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

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

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

As a result, the sql query statement was called only once, indicating that the second-level cache worked.
Second method:
The second method is to use @Cache + @Cacheable combination

@Entity  
@Table(name ="tablename")  
@Cacheable  
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)  
public class XxxEntity{}  

When the @Cache annotation is used, there is no need to configure the second-level cache strategy:

<property name="sharedCacheMode" value="ENABLE_SELECTIVE"></property>

Using the @Cache annotation is equivalent to the above configuration

Collection cache

a type of second level cache

@Entity 
@Table(name =”parent”) 
@Cacheable 
public class Parent{
private static final long serialVersionUID = 1L;  
private String name;  
private List<Children> clist;  

public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  

@OneToMany(fetch = FetchType.EAGER,mappedBy = "parent")  
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)  
public List<Children> getClist() {  
    return clist;  
}  
public void setClist(List<Children> clist) {  
    this.clist = clist;  
}  
}

Set the second-level cache on the collection property of the one-to-many relationship, and you can use the cache when querying the relationship.

Use hibernate's query query cache

First, the second-level cache is searched according to the object id. If you need to load a List, you need to use Query to query, and the query cache is used here.

String jpql = "FROM User u WHERE u.id = ?";
Query query = entityManager.createQuery(jpql);
query.setParameter(1, 1);
User user = (User) query.getSingleResult();

query = entityManager.createQuery(jpql);
query.setParameter(1, 1);
user = (User) query.getSingleResult();

Obviously, two queries will be executed.
write picture description here
Although the same session is used to query the same data, the cache is not used as found above.
If you want to use the cache and query only once, you can use setHint

String jpql = "FROM User u WHERE u.id = ?";
Query query = entityManager.createQuery(jpql).setHint(QueryHints.HINT_CACHEABLE, true);
query.setParameter(1, 1);
User user = (User) query.getSingleResult();

query = entityManager.createQuery(jpql).setHint(QueryHints.HINT_CACHEABLE, true);
query.setParameter(1, 1);
user = (User) query.getSingleResult();

You can see that the value is queried once.
write picture description here
The query query cache can use the second-level cache configuration that needs to be opened before, mainly configured:

<prop key="hibernate.cache.use_query_cache">true</prop>

spring Data jpa query cache

Need to configure:

<prop key="hibernate.cache.use_query_cache">true</prop>  

Put @QueryHint in the method to implement query caching
such as

@Query("from XxxEntity")  
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable",value ="true") })  
List<XxxEntity> findAllCached();

Note: In this way, the query cache will not take effect, that is, the findAll() method implemented by spring-data-jpa by default cannot be saved to the query cache

@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") }) 
List<XxxEntity> findAll(); 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326685506&siteId=291194637