Hibernate学习之二级缓存
© 版权声明:本文为博主原创文章,转载请注明出处
二级缓存
- 二级缓存又称“全局缓存”、“应用级缓存”
- 二级缓存中的数据可适用范围是当前应用的所有会话
- 二级缓存是可插拔式缓存,默认是EHCache
配置二级缓存步骤
- 添加二级缓存所需jar包
- 在hibernate.cfg.xml中开启二级缓存并配置二级缓存的提供类
- 添加二级缓存的属性配置文件
- 在需要被缓存的表所对应的映射文件中添加<cache/>标签
二级缓存数据
- 很少被修改的数据
- 不是很重要的数据,允许偶尔出现并发的数据
- 不会被高并发访问的数据
- 参考数据(eg.字典表等)
一二级缓存的对比

实例
1.项目结构

2.pom.xml
<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>org.proxy</groupId>
<artifactId>Hibernate-Ehcache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate.version>5.1.7.Final</hibernate.version>
</properties> <dependencies>
<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
<!-- ehcache -->
<!-- <dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency> -->
</dependencies>
</project>
3.Student.java
package org.hibernate.model;
import java.util.Date;
public class Student {
private long id;// 学号
private String name;// 姓名
private Date birthday;// 生日
private String sex;// 性别
public Student() {
}
public Student(long id, String name, Date birthday, String sex) {
this.id = id;
this.name = name;
this.birthday = birthday;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
4.Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping> <class name="org.hibernate.model.Student" table="STUDENT">
<cache usage="read-only"/><!-- 该表加入二级缓存 -->
<id name="id" type="java.lang.Long">
<column name="ID"/>
<generator class="assigned"/>
</id>
<property name="name" type="java.lang.String">
<column name="NAME"/>
</property>
<property name="birthday" type="date">
<column name="BIRTHDAY"/>
</property>
<property name="sex" type="java.lang.String">
<column name="SEX"/>
</property>
</class> </hibernate-mapping>
5.hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <!-- 配置SessionFactory -->
<session-factory>
<!-- 配置数据库连接信息 -->
<property name="connection.username">root</property>
<property name="connection.password">***</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql:///hibernate?useSSL=true&characterEncoding=UTF-8
</property> <!-- 配置常用属性 -->
<property name="hbm2ddl.auto">update</property><!-- 自动检查并创建表结构 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><!-- 方言 -->
<property name="show_sql">true</property><!-- 显示SQL语句 --> <!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 指定二级缓存的提供类 -->
<property name="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.EhCacheRegionFactory
</property> <!-- 引入映射文件 -->
<mapping resource="hbm/Student.hbm.xml"/>
</session-factory> </hibernate-configuration>
6.ehcache.xml
<ehcache>
<diskStore path="java.io.tmpdir"/><!-- 缓存文件保存路径 -->
<!-- 默认缓存设置
maxElementsInMemory:缓存的最大数量
eternal:设置元素是否是永久的。如果设置为true,则timeout失效
timeToIdleSeconds:设置元素过期前的空闲时间
timeToLiveSeconds:设置元素过期前的活动时间
overflowToDisk:当缓存中的数量达到限制后,是否保存到disk
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"/>
<cache name="Student"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"/>
</ehcache>
7.TestChcache.java
package org.hibernate.test; import java.util.Date; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.model.Student;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class TestChcache { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction; @Before
public void before() { sessionFactory = new Configuration().configure().buildSessionFactory();// 创建SessionFactory对象
session = sessionFactory.openSession();// 获取Session对象
transaction = session.beginTransaction();// 开启事务 } @After
public void after() { transaction.commit();// 提交事务
session.close();// 关闭Session
sessionFactory.close();// 关闭SessionFactory } @Test
public void init() { Student student = new Student(1L, "张三", new Date(), "男");
session.save(student); student = new Student(2L, "李四", new Date(), "男");
session.save(student); } @Test
public void testChcache() { Student student = session.get(Student.class, 1L);
System.out.println(student.getName()); session = sessionFactory.openSession();
student = session.get(Student.class, 1L);
System.out.println(student.getName()); } }
8.效果预览
8.1 首先执行init()方法,初始化表数据
8.2 屏蔽Student.hbm.xml中的<cache usage="read-only"/>,执行testChcache()方法

8.3 不屏蔽Student.hbm.xml中的<cache usage="read-only"/>,执行testChcache()方法

参考:http://www.imooc.com/video/9017
Hibernate学习之二级缓存的更多相关文章
- hibernate框架学习之二级缓存
缓存的意义 l应用程序中使用的数据均保存在永久性存储介质之上,当应用程序需要使用数据时,从永久介质上进行获取.缓存是介于应用程序与永久性存储介质之间的一块数据存储区域.利用缓存,应用程序可以将使用的数 ...
- Hibernate中 一 二级缓存及查询缓存(1)
最近趁有空学习了一下Hibernate的缓存,其包括一级缓存,二级缓存和查询缓存(有些是参照网络资源的): 一.一级缓存 一级缓存的生命周期和session的生命周期一致,当前sessioin ...
- Hibernate的一级二级缓存机制配置与测试
特别感谢http://www.cnblogs.com/xiaoluo501395377/p/3377604.html 在本篇随笔里将会分析一下hibernate的缓存机制,包括一级缓存(session ...
- hibernate 查询、二级缓存、连接池
hibernate 查询.二级缓存.连接池 查询: 1) 主键查询 Dept dept = (Dept) session.get(Dept.class, 12); Dept dept = (Dep ...
- hibernate 5的二级缓存案例讲解
hibernate 5的二级缓存案例讲解 本帖最后由 鱼丸儿 于 2018-1-20 11:44 编辑 大家好,今天来记录讲解一下磕磕绊绊的hibernate5 的二级缓存配置,一条路摸到黑 那么在这 ...
- Hibernate-ORM:16.Hibernate中的二级缓存Ehcache的配置
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 本篇博客讲述Hibernate中的二级缓存的配置,作者将使用的是ehcache缓存 一,目录 1.二级缓存的具 ...
- 具体解释Hibernate中的二级缓存
1.前言 这篇博客再前几篇博客的基础上来解说一下.Hibernate中的二级缓存.二级缓存是属于SessionFactory级别的缓存机制. 第一级别的缓存是Session级别的缓存,是属于事务范围的 ...
- hibernate框架学习之二级缓存(测试用例)
HqlDemoApp.java package cn.itcast.h3.query.hql; import java.io.Serializable; import org.hibernate.Qu ...
- Hibernate+EhCache配置二级缓存
步骤: 第一步:加入ehcache.jar 第二步: 在src目录下新建一个文件,名为:ehcache.xml 第三步:在hibernate配置文件的<session-factory>下配 ...
随机推荐
- Javascript短路表达式
短路表达式:作为"&&"和"||"操作符的操作数表达式,这些表达式在进行求值时,只要最终的结果已经可以确定是真或假,求值过程便告终止,这称之为短 ...
- HihoCoder 1629 Graph (2017 ACM-ICPC 北京区域赛 C题,回滚莫队 + 启发式合并 + 可撤销并查集)
题目链接 2017 ACM-ICPC Beijing Regional Contest Problem C 题意 给定一个$n$个点$m$条边的无向图.现在有$q$个询问,每次询问格式为$[l, ...
- H. Fake News (medium)
H. Fake News (medium) 题意 以前是给出 S T 串,问在 S 中有多少个子串为 T 的个数,子串可以不连续,保持位置相对一致. 现在给出 n ,要你构造 S T 串. 分析 这种 ...
- 测试工具APPScan安装与使用教程
- 洛谷——P1093 奖学金
P1093 奖学金 题目描述 某小学最近得到了一笔赞助,打算拿出其中一部分为学习成绩优秀的前5名学生发奖学金.期末,每个学生都有3门课的成绩:语文.数学.英语.先按总分从高到低排序,如果两个同学总分相 ...
- SQL 增删改查 复习
首先创建两张表 CREATE TABLE Teacher ( Id ,) NOT NULL PRIMARY KEY, Name ) NOT NULL, ); CREATE TABLE Student ...
- 【MySQL】undo,redo,2PC,恢复思维导图
http://blog.itpub.net/22664653/viewspace-2131353/
- JAVA常见算法题(十七)
package com.xiaowu.demo; //输出九九乘法表. public class Demo17 { public static void main(String[] args) { t ...
- crossapp里的位置设置
crossapp里有Frame.Center,这两种都是可以用来确定一个view的位置和大小. 不同点:Frame定位是以View的左上角为参照点,Center是以View的中心点为参照点 注意cro ...
- ElasticSearch 监控单个节点详解
1.介绍 集群健康 就像是光谱的一端——对集群的所有信息进行高度概述. 而 节点统计值 API 则是在另一端.它提供一个让人眼花缭乱的统计数据的数组,包含集群的每一个节点统计值. 节点统计值 提供的统 ...