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-二级缓存的更多相关文章

  1. 使用OSCache优化性能,及JPA二级缓存

    1.使用静态化页面技术: 要统计产品的浏览次数: 在<body> <img src="http://www.site.com/data/count.do?productId ...

  2. 【SSH网上商城项目实战16】Hibernate的二级缓存处理首页的热门显示

    转自:https://blog.csdn.net/eson_15/article/details/51405911 网上商城首页都有热门商品,那么这些商品的点击率是很高的,当用户点击某个热门商品后需要 ...

  3. SpringMVC +Spring + MyBatis + Mysql + Redis(作为二级缓存) 配置

    转载:http://blog.csdn.net/xiadi934/article/details/50786293 项目环境: 在SpringMVC +Spring + MyBatis + MySQL ...

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

    一级缓存 查询两次id为1的user User user1 = entityManager.find(User.class, 1); User user2 = entityManager.find(U ...

  5. JPA学习(五、JPA_二级缓存)

    框架学习之JPA(五) JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中 ...

  6. JPA(5)使用二级缓存

    jpa的缓存分为一级缓存和二级缓存,一级缓存值得是会话级别的,而二级缓存是跨会话级别的. 使用二级缓存,使用到了Ehcache,首先第一步需要在配置文件中配置使用了二级缓存 <shared-ca ...

  7. Hibernate JPA 中配置Ehcache二级缓存

    在Hibernate3 JPA里配置了一下非分布式环境的二级缓存,效果不错.具体过程如下: 1, 需要引入的jar包 http://ehcache.org/downloads/catalog 下载的包 ...

  8. spring boot集成ehcache 2.x 用于hibernate二级缓存

    https://www.jianshu.com/p/87b2c309b776 本文将介绍如何在spring boot中集成ehcache作为hibernate的二级缓存.各个框架版本如下 spring ...

  9. Spring 整合 Hibernate 时启用二级缓存实例详解

    写在前面: 1. 本例使用 Hibernate3 + Spring3: 2. 本例的查询使用了 HibernateTemplate: 1. 导入 ehcache-x.x.x.jar 包: 2. 在 a ...

  10. 探索ASP.NET MVC5系列之~~~5.缓存篇(页面缓存+二级缓存)

    其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...

随机推荐

  1. PHP微信支付案例收录

    微信支付API 文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1# TP 微信 + 支 ...

  2. nginx gzip 以及 tcp 反向代理的 model

    同事为了提高性能发给我一model 简单改了一下. 记录一下 #user nobody; worker_processes ; events { worker_connections ; } http ...

  3. [转帖]DevOps/TestOps概念

    发现收藏不好用..还是转吧.. https://www.cnblogs.com/fnng/p/8232410.html DevOps/TestOps概念 2018-01-07 22:02 by 虫师, ...

  4. 使用DataContext和ItemsSource将数据源绑定到ListView上的区别

    在最近的一个项目中,将DataView类型的数据源绑定到ListView控件时,发现当DataView的内容发生变化时,前台的ListView控件的内容并没有发生改变,在这里我先贴出前台要绑定数据源的 ...

  5. CSS等高布局的7种方式

    前面的话 等高布局是指子元素在父元素中高度相等的布局方式.等高布局的实现包括伪等高和真等高,伪等高只是看上去等高而已,真等高是实实在在的等高.本文将介绍边框模拟.负margin这两种伪等高以及tabl ...

  6. 将关系型数据库抽取成redis的思路

    思路是 先把id抽取出来形成一个·list表示数量 然后再把表变成键值对形式把id当做成键

  7. checkStyle 错误普及

    1Type is missing a javadoc commentClass  缺少类型说明 2“{” should be on the previous line“{” 应该位于前一行.解决方法: ...

  8. Luogu5055 【模板】可持久化文艺平衡树(fhq-treap)

    注意下传标记时也需要新建节点.空间开的尽量大. #include<iostream> #include<cstdio> #include<cmath> #inclu ...

  9. MT【242】图像几何意义

    设函数$f(x)=x^2+ax+b$,已知函数$f(x)$在$[-1,1]$上存在零点,若$0\le b-2a\le 1$,求$b$的范围 (2015浙江文科高考20(2)) 分析:理解成$g(x)= ...

  10. Linux Install geoip

    安装方法 http://php.net/manual/en/geoip.installation.phpgeoip中的PHP函数介绍:http://php.net/manual/en/book.geo ...