JPA(5)使用二级缓存

jpa的缓存分为一级缓存和二级缓存,一级缓存值得是会话级别的,而二级缓存是跨会话级别的。

  使用二级缓存,使用到了Ehcache,首先第一步需要在配置文件中配置使用了二级缓存

<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> 

注意:既然是二级缓存。那么当然需要知道缓存哪些东西和使用什么jpa产品(这是我自己理解的),所以这个配置必须在最后面,

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">
        
        
        
        <!-- 配置使用什么ORM产品 -->
        <!--
        需要注意的是:
        1.实现的ORM策略是继承 javax.persistence.spi.PersistenceProvide接口,
        2如果项目中只有一个JPA实现产品,那么不指定也是可以的
        
         -->
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        
        <!-- 添加持久化类 -->
        
        <class>com.hotusm.commom.entity.User</class>
        <class>com.hotusm.commom.entity.Phone</class>
        <class>com.hotusm.commom.entity.FirstLover</class>
        <class>com.hotusm.commom.entity.Teacher</class>
        <class>com.hotusm.commom.entity.Student</class>
        <class>com.hotusm.commom.entity.Food</class>
        
        <!-- 添加二级缓存的策略
        ALL:所以的实体类都被缓存
        NONE:所以的实体都不被缓存
        ENABLE_SELECTIVE:标示了@Cacheable(true)的实体会被缓存
        DISABLE_SELECTIVE:缓存除了标示@Cacheable(true)的实体
        UNSPECIFIFD:默认值。JPA产品默认值将会使用,这个要看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="1234"/>
            
            <!-- 配置jpa实现产品 -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.format_sql" value="true"/>
            <!-- 使用二级缓存 -->
            <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>
    </persistence-unit>
    
</persistence>

,这样我们就可以在实体类的上面配置@Cacheable来指定是否使用二级缓存,

原文地址:https://www.cnblogs.com/zr520/p/5024127.html