1、缓存(Cache): 介于应用程序和永久性数据存储源(如硬盘上的文件或者数据库)之间,其作用是降低应用程序直接读写永久性数据存储源的频率,从而提高应用的运行性能。缓存中的数据是数据存储源中数据的拷贝。缓存的物理介质通常是内存
2、Hibernate的缓存级别
①一级缓存:Session 级别的缓存,它是属于事务范围的缓存,归Hibernate管理
②二级缓存:SessionFactory 级别的缓存,它是属于进程范围的缓存
3、SessionFactory 缓存分类:
①内置缓存:Hibernate 自带的, 不可卸载. 通常在 Hibernate 的初始化阶段, Hibernate 会把映射元数据和预定义的 SQL 语句放到 SessionFactory 的缓存中, 映射元数据是映射文件中数据(.hbm.xml 文件中的数据)的复制. 该内置缓存是只读的
②外置缓存(二级缓存):一个可配置的缓存插件. 在默认情况下, SessionFactory 不会启用这个缓存插件. 外置缓存中的数据是数据库数据的复制, 外置缓存的物理介质可以是内存或硬盘
4、二级缓存使用情况:
(1)适合使用:①不需要经常修改 ②不重要的数据 ③允许并发的数据
(2)不适合使用:①需要经常修改 ②重要的数据 ③共享的数据
5、事务隔离级别(与hibernate配置中的对应):
①非严格读写(Nonstrict-read-write): 不保证缓存与数据库中数据的一致性. 对于极少被修改, 而且允许脏读的数据, 可以采用这种策略
②读写型(Read-write): 对于经常读但是很少被修改的数据, 可以采用这种隔离类型, 可以防止脏读
③事务型(Transactional): 仅在受管理环境下适用. 对于经常读但是很少被修改的数据, 可以采用这种隔离类型, 可以防止脏读和不可重复读
④只读型(Read-Only):对于从来不会被修改的数据, 可以采用这种访问策略
6、Hibernate缓存插件:
①EHCache: 可作为进程范围内的缓存, 存放数据的物理介质可以使内存或硬盘, 对 Hibernate 的查询缓存提供了支持
②OSCache:可作为进程范围内的缓存, 存放数据的物理介质可以使内存或硬盘, 提供了丰富的缓存数据过期策略, 对 Hibernate 的查询缓存提供了支持
③SwarmCache: 可作为集群范围内的缓存, 但不支持 Hibernate 的查询缓存
④JBossCache:可作为集群范围内的缓存, 支持 Hibernate 的查询缓存
注意事项:
EHCache、OSCache支持非严格读写/读写型/只读型事务隔离级别,只有JBossCache支持事务型隔离级别,所以一般情况下使用EHCache,事务型隔离级别时使用JBossCache即可
7、缓存配置使用步骤:
(1)导入jar包
(2)在src文件夹下创建ehcache.xml
(3)配置 hibernate.cfg.xml(启用 hibernate 的二级缓存、配置hibernate二级缓存使用的产品、在hibernate.xml中配置对哪些类使用 hibernate 的二级缓存或类对应的映射关系文件中配置使用二级缓存)
(4)在逻辑里面使用查询的代码就可以了
8、HQLone.java
package com.demo.sshtest;
import java.util.HashSet;
import java.util.Set;
public class HQLone {
public Integer id;
public String firstNameOne;
public String lastNameOne;
public int number;
public Set<HQLtwo> hqLtwo = new HashSet<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstNameOne() {
return firstNameOne;
}
public void setFirstNameOne(String firstNameOne) {
this.firstNameOne = firstNameOne;
}
public String getLastNameOne() {
return lastNameOne;
}
public void setLastNameOne(String lastNameOne) {
this.lastNameOne = lastNameOne;
}
public Set<HQLtwo> getHqLtwo() {
return hqLtwo;
}
public void setHqLtwo(Set<HQLtwo> hqLtwo) {
this.hqLtwo = hqLtwo;
}
@Override
public String toString() {
return "HQLone [id=" + id + "]";
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public HQLone(){}
public HQLone(Integer id, String firstNameOne, int number) {
super();
this.id = id;
this.firstNameOne = firstNameOne;
this.number = number;
}
}
9、HQLtwo.java
package com.demo.sshtest;
import java.util.HashSet;
import java.util.Set;
public class HQLtwo {
public Integer id;
public String firstNameTwo;
public String lastNameTwo;
public Set<HQLone> hqLone = new HashSet<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstNameTwo() {
return firstNameTwo;
}
public void setFirstNameTwo(String firstNameTwo) {
this.firstNameTwo = firstNameTwo;
}
public String getLastNameTwo() {
return lastNameTwo;
}
public void setLastNameTwo(String lastNameTwo) {
this.lastNameTwo = lastNameTwo;
}
public Set<HQLone> getHqLone() {
return hqLone;
}
public void setHqLone(Set<HQLone> hqLone) {
this.hqLone = hqLone;
}
}
10、HQLone.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-4-19 14:19:30 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.demo.sshtest.HQLone" table="HQLONE">
<!--
<cache usage="read-write"/>
-->
<id name="id" type="java.lang.Integer">
<column name="ONE_ID" />
<generator class="native" />
</id>
<property name="firstNameOne" type="java.lang.String">
<column name="FIRSTNAMEONE" />
</property>
<property name="lastNameOne" type="java.lang.String">
<column name="LASTNAMEONE" />
</property>
<property name="number" type="java.lang.Integer">
<column name="NUMBER" />
</property>
<set name="hqLtwo" table="HQLONE_HQLTWO" inverse="false" lazy="true">
<key>
<column name="ONE_ID" />
</key>
<many-to-many class="com.demo.sshtest.HQLtwo" column="TWO_ID"/>
</set>
</class>
</hibernate-mapping>
11、HQLtwo.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-4-19 14:19:30 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.demo.sshtest.HQLtwo" table="HQLTWO">
<id name="id" type="java.lang.Integer">
<column name="TWO_ID" />
<generator class="native" />
</id>
<property name="firstNameTwo" type="java.lang.String">
<column name="FIRSTNAMETWO" />
</property>
<property name="lastNameTwo" type="java.lang.String">
<column name="LASTNAMETWO" />
</property>
<set name="hqLone" table="HQLONE_HQLTWO" inverse="true" lazy="true">
<!--
<cache usage="read-write"/>
-->
<key>
<column name="TWO_ID" />
</key>
<many-to-many class="com.demo.sshtest.HQLone" column="ONE_ID"/>
</set>
</class>
</hibernate-mapping>
12、ehcache.xml 二级缓存需要用到的,要配置在src下
<ehcache>
<!--
指定一个目录:当 EHCache 把数据写到硬盘上时, 将把数据写到这个目录下.
-->
<diskStore path="E:/workspace"/>
<!--
设置缓存的默认数据过期策略
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!--
设定具体的命名缓存的数据过期策略。每个命名缓存代表一个缓存区域
缓存区域(region):一个具有名称的缓存块,可以给每一个缓存块设置不同的缓存策略。
如果没有设置任何的缓存区域,则所有被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../>
Hibernate 在不同的缓存区域保存不同的类/集合。
对于类而言,区域的名称是类名。如:com.atguigu.domain.Customer
对于集合而言,区域的名称是类名加属性名。如com.atguigu.domain.Customer.orders
-->
<!--
name: 设置缓存的名字,它的取值为类的全限定名或类的集合的名字
maxElementsInMemory: 设置基于内存的缓存中可存放的对象最大数目
eternal: 设置对象是否为永久的, true表示永不过期,
此时将忽略timeToIdleSeconds 和 timeToLiveSeconds属性; 默认值是false
timeToIdleSeconds:设置对象空闲最长时间,以秒为单位, 超过这个时间,对象过期。
当对象过期时,EHCache会把它从缓存中清除。如果此值为0,表示对象可以无限期地处于空闲状态。
timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。
如果此值为0,表示对象可以无限期地存在于缓存中. 该属性值必须大于或等于 timeToIdleSeconds 属性值
overflowToDisk:设置基于内存的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中
-->
<cache name="com.demo.sshtest.HQLone"
maxElementsInMemory="1"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="com.demo.sshtest.HQLone.hqLtwo"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
</ehcache>
13、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>
<session-factory>
<!-- 配置连接数据库基本信息 -->
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- localhost是地址,如果用默认可以不写localhost,hebernateTEST是数据库名 -->
<property name="connection.url">jdbc:mysql://localhost/hebernateTEST</property>
<!-- 配置hibernate基本信息-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 执行操作室是否在控制台打印sql -->
<property name="show_sql">true</property>
<!-- 是否对sql格式化 -->
<property name="format_sql">true</property>
<!-- 指定自动生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property>
<!-- 设置 Hibernate 的事务隔离级别 -->
<property name="connection.isolation">2</property>
<!-- 设置调用delete()时,OID变成null -->
<property name="hibernate.use_identifier_rollback">true</property>
<!--C3P0 数据库连接池-->
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.timeout">2000</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.idle_test_period">2000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<!--设定JDBC的statement读取数据-->
<property name="hibernate.jdbc.fetch_size">100</property>
<property name="hibernate.jdbc.batch_size">50</property>
<!-- 启用二级缓存 -->
<property name="cache.use_second_level_cache">true</property>
<!-- 配置使用的二级缓存的产品 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 配置启用查询缓存 -->
<property name="cache.use_query_cache">true</property>
<!-- 指定关联的 *.hbm.xml文件(目录结构) 每个.hbm.xml对应一个数据表-->
<mapping resource="com/demo/sshtest/HQLone.hbm.xml"/>
<mapping resource="com/demo/sshtest/HQLtwo.hbm.xml"/>
<!-- 设置使用二级缓存的类或类里面的集合对象 -->
<class-cache usage="read-write" class="com.demo.sshtest.HQLone"/>
<class-cache usage="read-write" class="com.demo.sshtest.HQLtwo"/>
<collection-cache usage="read-write" collection="com.demo.sshtest.HQLone.hqLtwo"/>
</session-factory>
</hibernate-configuration>
14、testSecLevelSession.java
package com.demo.sshtest;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class testSecLevelSession {
//使用jar包:ehcache-core-2.4.3.jar、hibernate-ehcache-4.2.4.Final.jar、slf4j-api-1.6.1.jar
//使用步骤
//(1)导入jar包
//(2)在src文件夹下创建ehcache。xml
//(3)配置 hibernate.cfg.xml
// ①配置启用 hibernate 的二级缓存
// <property name="cache.use_second_level_cache">true</property>
// ②配置hibernate二级缓存使用的产品
// <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
// ③在hibernate.xml中配置对哪些类使用 hibernate 的二级缓存<class-cache usage="read-write" class=""/>
// 或
// 在类对应的映射关系文件中配置使用二级缓存<cache usage="read-write"/>
//(4)在逻辑里面使用查询的代码就可以了
//注意事项:
//(1)对类或者集合对象配置使用二级缓存时,可以配置在hibernate.xml中,也可以配置在关系映射文件中
// ①在hibernate.xml中配置
// <class-cache usage="read-write" class="全类名"/>
// <collection-cache usage="read-write" collection="全类名加集合对象名"/>
// ②在关系映射文件中配置
// 在class标签下和set标签下写<cache usage="read-write"/>
//(2)持久化类里面有集合对象的时候,要配置上集合元素使用二级缓存,不然查询数据库次数会变多
//(3)HQL 及 QBC 查询时
// ①默认情况下, 设置的缓存对 HQL 及 QBC 查询时无效的
// ②在 hibernate 配置文件中声明开启查询缓存<property name="cache.use_query_cache">true</property>
// ③调用 Query 或 Criteria 的 setCacheable(true) 方法
public SessionFactory sessionFactory;
public Session session;
public Transaction transaction;
@Before
public void init(){
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
System.out.println("init");
}
@After
public void destory(){
transaction.commit();
session.close();
sessionFactory.close();
System.out.println("destory");
}
@Test
public void insertOriData(){
//插入测试数据
for(int number=1;number<10;number++){
for(int i=0;i<2;i++){
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String time = simpleDateFormat.format(date);
HQLone hqLone1 = new HQLone();
HQLone hqLone2 = new HQLone();
HQLtwo hqLtwo1 = new HQLtwo();
HQLtwo hqLtwo2 = new HQLtwo();
hqLone1.setFirstNameOne("1FNameOne_"+time);
hqLone1.setLastNameOne("1LNameOne_"+time);
hqLone1.setNumber(number);
hqLone2.setFirstNameOne("1FNameTwo_"+time);
hqLone2.setLastNameOne("1LNameTwo_"+time);
hqLone2.setNumber(number);
hqLtwo1.setFirstNameTwo("2FNameOne_"+time);
hqLtwo1.setLastNameTwo("2LNameOne_"+time);
hqLtwo2.setFirstNameTwo("2FNameTwo_"+time);
hqLtwo2.setLastNameTwo("2LNameTwo_"+time);
hqLone1.getHqLtwo().add(hqLtwo1);
hqLone1.getHqLtwo().add(hqLtwo2);
hqLone2.getHqLtwo().add(hqLtwo1);
hqLone2.getHqLtwo().add(hqLtwo2);
hqLtwo1.getHqLone().add(hqLone1);
hqLtwo1.getHqLone().add(hqLone2);
hqLtwo2.getHqLone().add(hqLone1);
hqLtwo2.getHqLone().add(hqLone2);
session.save(hqLone1);
session.save(hqLone2);
session.save(hqLtwo1);
session.save(hqLtwo2);
}
}
}
@Test
public void testCollectionSecondLevelCache(){
HQLone hqLone = (HQLone) session.get(HQLone.class, 1);
System.out.println(hqLone.getHqLtwo());
System.out.println(hqLone.getHqLtwo().size());
transaction.commit();
session.close();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
HQLone hqLone2 = (HQLone) session.get(HQLone.class, 1);
System.out.println(hqLone2.getHqLtwo().size());
}
@Test
public void testQueryCache(){
Query query = session.createQuery("FROM HQLone");
query.setCacheable(true);
List<HQLone> emps = query.list();
System.out.println(emps.size());
emps = query.list();
System.out.println(emps.size());
Criteria criteria = session.createCriteria(HQLone.class);
criteria.setCacheable(true);
}
@Test
public void testUpdateTimeStampCache(){
Query query = session.createQuery("FROM HQLone");
query.setCacheable(true);
List<HQLone> emps = query.list();
System.out.println(emps.size());
HQLone hqLone = (HQLone) session.get(HQLone.class, 1);
hqLone.setNumber(666);
emps = query.list();
System.out.println(emps.size());
}
@Test
public void testQueryIterate(){
HQLone hqLone = (HQLone) session.get(HQLone.class, 1);
System.out.println(hqLone.getHqLtwo().size());
Query query = session.createQuery("FROM HQLone e WHERE e.id = 1");
Iterator<HQLone> hqloneIT = query.iterate();
while(hqloneIT.hasNext()){
HQLone record = hqloneIT.next();
System.out.println(record.getId()+"-"+record.getFirstNameOne()+"-"+record.getLastNameOne()+"-"+record.getNumber());
}
}
}
15、项目目录
16、demo
https://download.csdn.net/download/qq_22778717/10372555