10、JPA-二级缓存
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com</groupId>
<artifactId>jpa</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>5.4.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<!-- 指定jdk -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build> </project>
persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="jpaname"> <!-- 实体类 -->
<class>com.jpa.yingshe.Customer</class> <properties>
<!-- 数据库信息 -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.8.136/jpa?useSSL=false"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/> <!-- 配置 hibernate 属性 -->
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Customer
package com.jpa.yingshe; import javax.persistence.*; @Table(name = "JPA_CUTOMERS")
@Entity
public class Customer { private Integer id;
private String lastName; private String email; public Customer() {
} public Customer(String lastName) {
this.lastName = lastName;
} @GeneratedValue(strategy = GenerationType.AUTO)
@Id
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} @Column(name = "LAST_NAME", length = 50, nullable = false)
public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
}
}
测试
先看JPA自带的一级缓存
package jpa.test; import com.jpa.yingshe.Customer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence; public class JPAyingshe {
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction transaction; @Before
public void init() {
entityManagerFactory = Persistence.createEntityManagerFactory("jpaname");
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
} @After
public void destroy() {
transaction.commit();
entityManager.close();
entityManagerFactory.close();
} @Test
public void testFirstLevelCache() {
Customer customer1 = entityManager.find(Customer.class, 1);
Customer customer2 = entityManager.find(Customer.class, 1);
}
}

中间关闭会话再试试
@Test
public void testFirstLevelCache() {
Customer customer1 = entityManager.find(Customer.class, 1); transaction.commit();
entityManager.close(); entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin(); Customer customer2 = entityManager.find(Customer.class, 1);
}

配置二级缓存,让关闭会话后也只发送一次查询
添加 ehcache 依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.6.3</version>
</dependency>
添加 ehcache.xml 配置
<ehcache>
<diskStore path="./target/tmp"/> <defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/> <cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/> <cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->
</ehcache>
修改 persistence.xml 配置
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="jpaname" transaction-type="RESOURCE_LOCAL"> <!-- 配置使用什么 ORM 产品来作为 JPA 的实现 -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <!-- 实体类 -->
<class>com.jpa.yingshe.Customer</class> <!--
配置二级缓存的策略
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.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.8.136/jpa?useSSL=false"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/> <!-- 配置 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.internal.EhcacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
</properties>
</persistence-unit>
</persistence>
修改实体类,添加缓存注解
@Cacheable
@Table(name = "JPA_CUTOMERS")
@Entity
public class Customer { private Integer id;
查询
@Test
public void testSecondLevelCache() {
Customer customer1 = entityManager.find(Customer.class, 1); transaction.commit();
entityManager.close(); entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin(); Customer customer2 = entityManager.find(Customer.class, 1);
}

项目结构

官方文档
10、JPA-二级缓存的更多相关文章
- 使用OSCache优化性能,及JPA二级缓存
1.使用静态化页面技术: 要统计产品的浏览次数: 在<body> <img src="http://www.site.com/data/count.do?productId ...
- 【SSH网上商城项目实战16】Hibernate的二级缓存处理首页的热门显示
转自:https://blog.csdn.net/eson_15/article/details/51405911 网上商城首页都有热门商品,那么这些商品的点击率是很高的,当用户点击某个热门商品后需要 ...
- SpringMVC +Spring + MyBatis + Mysql + Redis(作为二级缓存) 配置
转载:http://blog.csdn.net/xiadi934/article/details/50786293 项目环境: 在SpringMVC +Spring + MyBatis + MySQL ...
- JPA学习笔记(11)——使用二级缓存
一级缓存 查询两次id为1的user User user1 = entityManager.find(User.class, 1); User user2 = entityManager.find(U ...
- JPA学习(五、JPA_二级缓存)
框架学习之JPA(五) JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中 ...
- JPA(5)使用二级缓存
jpa的缓存分为一级缓存和二级缓存,一级缓存值得是会话级别的,而二级缓存是跨会话级别的. 使用二级缓存,使用到了Ehcache,首先第一步需要在配置文件中配置使用了二级缓存 <shared-ca ...
- Hibernate JPA 中配置Ehcache二级缓存
在Hibernate3 JPA里配置了一下非分布式环境的二级缓存,效果不错.具体过程如下: 1, 需要引入的jar包 http://ehcache.org/downloads/catalog 下载的包 ...
- spring boot集成ehcache 2.x 用于hibernate二级缓存
https://www.jianshu.com/p/87b2c309b776 本文将介绍如何在spring boot中集成ehcache作为hibernate的二级缓存.各个框架版本如下 spring ...
- Spring 整合 Hibernate 时启用二级缓存实例详解
写在前面: 1. 本例使用 Hibernate3 + Spring3: 2. 本例的查询使用了 HibernateTemplate: 1. 导入 ehcache-x.x.x.jar 包: 2. 在 a ...
- 探索ASP.NET MVC5系列之~~~5.缓存篇(页面缓存+二级缓存)
其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...
随机推荐
- 20172319 《Java程序设计教程》第8周学习总结
20172319 2018.04.24-05.03 <Java程序设计教程>第8周学习总结 目录 教材学习内容总结 教材学习中的问题和解决过程 代码调试中的问题和解决过程 代码托管 上周考 ...
- Quartz中时间表达式的设置-----corn表达式 (转)(http://www.cnblogs.com/GarfieldTom/p/3746290.html)
Quartz中时间表达式的设置-----corn表达式 (注:这是让我看比较明白的一个博文,但是抱歉,没有找到原作者,如有侵犯,请告知) 时间格式: <!-- s m h d m w(?) y( ...
- vCenter 异常关机后无法开启ESXi虚拟机的处理.
春节假期一个插排掉电了, 然后vcenter不幸自动关机了. 对虚拟机进行开机时错误提示 前期更改过administrator的密码, 但是忘记同步修改sqlserver启动时的用户了(这里使用adm ...
- SAP顾问岗位要求
岗位职责: 1.负责SAP系统各模块日常运维工作,解决用户在系统操作过程中遇到的问题: 2.评估用户需求(新需求.功能优化)的可实现性,完成SAP系统及相关系统的配置调整及功能实现: 3.负责CRM等 ...
- Linux基础学习(4)--Linux常用命令
第四章——Linux常用命令 一.文件处理命令 1.命令格式与目录处理命令ls: (1)命令格式:命令 [-选项] [参数] 例:ls -la /etc (2)说明:个别命令使用不遵循此格式;当有 ...
- maven项目使用本地jar包
问题描述 今天自己写demo需要用到jodconverter-2.2.2.jar,但是maven库中只有2.2.1的版本.我看网上有提供jar包的.于是我下载下来,但是怎么引用到pom文件中呢?并且保 ...
- C-Lodop回调函数的触发
高版本的火狐和谷歌不再支持np插件之后,Lodop公司推出了C-Lodop,解决了这些浏览器不能用Lodop插件方式打印的问题,相比较Lodop插件,C-Lodop由于是以服务的形式出现,返回值不能直 ...
- Django的datetime.timedelta类(Django编程-2)
datetime.timedelta对象代表两个时间之间的时间差,两个date或datetime对象相减就可以返回一个timedelta对象. 如果有人问你昨天是几号,这个很容易就回答出来了.但是如果 ...
- BZOJ3322[Scoi2013]摩托车交易——最大生成树+贪心+倍增
题目描述 mzry1992 在打完吊针出院之后,买了辆新摩托车,开始了在周边城市的黄金运送生意.在mzry1992 生活的地方,城市之间是用双向高速公路连接的.另外,每条高速公路有一个载重上限,即在不 ...
- 牛客国庆集训派对Day2 H 期望
小贝喜欢玩卡牌游戏.某个游戏体系中共有N种卡牌,其中M种是稀有的.小贝每次和电脑对决获胜之后都会有一个抽卡机会,这时系统会随机从N种卡中选择一张给小贝.普通卡可能多次出现,而稀有卡牌不会被重复抽到.小 ...