hibernate一级缓存及二级缓存的区别
什么是缓存
缓存是介于物理数据源与应用程序之间,是对数据库中的数据复制一份临时放在内存中的容器,其作用是为了减少应用程序对物理数据源访问的次数,从而提高了应用程序的运行性能。Hibernate在进行读取数据的时候,根据缓存机制在相应的缓存中查询,如果在缓存中找到了需要的数据(我们把这称做“缓存命中"),则就直接把命中的数据作为结果加以利用,避免了大量发送SQL语句到数据库查询的性能损耗。
一级缓存和二级缓存
一级缓存
一级缓存也称session缓存(事务缓存):hibernate内置的,不能卸除,只要使用了hibernate的session就会使用到缓存机制。
缓存范围
缓存只能被当前session对象使用,缓存的生命周期依赖于session的生命周期,当session关闭就会清理缓存,clear也能清理缓存,而evict方法可以清理指定的缓存。
二级缓存
二级缓存也称SessionFactory缓存(应用缓存):使用第三方插件,可插拔。
缓存范围
缓存被应用范围内的所有session共享,不同的Session可以共享。这些session有可能是并发访问缓存,因此必须对缓存进行更新。缓存的生命周期依赖于应用的生命周期,应用结束时,缓存也就结束了生命周期,二级缓存存在于应用程序范围。
缓存的应用场景?
例如很少修改或者根本不修改的数据
就像字典数据(数据庞大且较少更新)
耗时较高的统计sql,电话账单查询……
ehcache概念
ehcache是一个纯java的进程内缓存框架,具有配置简单、结构清晰、功能强大的特点。
而他的2.X版本和3.X相比而言,3.x的版本和2.x的版本API差异比较大。
本次介绍的是2.X版本。
ehcache的特点
够快、够简单、够袖珍、够轻量、好扩展、提供缓存管理器监听器、支持分布式缓存。
cacheManager(缓存管理器)的使用
缓存管理器内可以放置若干cache(缓存对象),存放数据的实质,所有cache都实现了Ehcache接口。
顺序层次:ehcache.xml->CacheManager->Cache->Element(javabean),缓存对象及其属性都可序列化。
ehcache的使用
导入相关依赖:
pom.xml
需要去中央仓库中寻找其jar包依赖(注意ehcache是net相关的那一个,不是org相关的ehcache):
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wangqiuping</groupId>
<artifactId>Cache</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>hibrenate Maven Webapp</name>
<url>http://maven.apache.org</url>
<!--相关版本的配置-->
<properties>
<servlet.version>4.0.1</servlet.version>
<junit.version>3.8.1</junit.version>
<MySQL.version>5.1.44</MySQL.version>
<jstl.version>1.2</jstl.version>
<hibernate.version>5.2.12.Final</hibernate.version>
<ehcache.version>2.10.0</ehcache.version>
</properties>
<dependencies>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- MySQL -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${MySQL.version}</version>
</dependency>
<!-- jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- taglibs-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- tomcat -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>8.5.56</version>
</dependency>
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!--ehcache-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!-- ehcache与hibernate的桥接包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.12.Final</version>
</dependency>
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- slf4j相关依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
<scope>runtime</scope>
</dependency>
<!--用于与slf4j保持桥接 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.9.1</version>
</dependency>
<!--核心log4j2jar包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.9.1</version>
</dependency>
<!--核心log4j2j相关依赖 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.1</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.9.1</version>
<scope>runtime</scope>
</dependency>
<!--需要使用log4j2的AsyncLogger需要包含disruptor -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
<build>
<finalName>Cache</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
接下来是配置缓存文件参数(ehcache.xml):
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<defaultCache eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"/>
<cache name="bookCache" eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
相关参数解释:
属性 | 解释 |
---|---|
diskStore | 指的是磁盘存储(将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存) |
defaultCache | 默认的管理策略 |
path | 指定在硬盘上存储对象的路径 |
java.io.tmpdir | 默认的临时文件路径 |
eternal | 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断 |
maxElementsInMemory | 在内存中缓存的element的最大数目 |
overflowToDisk | 如果内存中数据超过内存限制,是否要缓存到磁盘上 |
diskPersistent | 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false |
timeToIdleSeconds | 对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问 |
imeToLiveSeconds | 对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问 |
memoryStoreEvictionPolicy | 缓存的3 种清空策略 |
FIFO | first in first out (先进先出) |
LFU | 缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存 |
LRU | ehcache 默认值,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存) |
name | Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里) |
hibernate.cfg.xml中添加二级缓存配置
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
完整的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">123</property>
<!-- 链接的绝对路径 -->
<property name="connection.url">
jdbc:mysql://localhost:3306/t243?useUnicode=true&characterEncoding=UTF-8&userSSL=false
</property>
<!-- 驱动的绝对路径 -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- 数据库方言配置 -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- 调试相关配置 -->
<!-- hibernate运行过程是否展示自动生成的SQL代码 -->
<property name="show_sql">true</property>
<!-- 是否规范化输出SQL代码 -->
<property name="format_sql">true</property>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 实体映射相关配置 -->
<mapping resource="com/wangqiuping/entity/Book.hbm.xml"/>
<mapping resource="com/wangqiuping/entity/Category.hbm.xml"/>
</session-factory>
</hibernate-configuration>
需要的工具类:
EhcacheUtil
package com.zengjing.util;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import java.io.InputStream;
public class EhcacheUtil {
//定义的cachManager缓存管理器,用于存储Cache缓存对象
private static CacheManager cacheManager;
static {
try {
//加载根路径下的ehcache.xml并转换为输入流
InputStream is=EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
cacheManager = CacheManager.create(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private EhcacheUtil() {
}
/**
* 往缓存管理器CachManager中指定存储对象Cache中存储数据
* @param cacheName 缓存对象名
* @param key 缓存元素名称
* @param value 缓存元素的值
*/
public static void put(String cacheName, Object key, Object value) {
//根据缓存对象名获取缓存管理器中的指定缓存对象
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
//以默认配置添加一个名叫cacheName的Cache
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
}
//创建一个Element缓存元素,并将缓存元素添加到Cache缓存对象中
cache.put(new Element(key, value));
}
/**
* 根据缓存对象名获取缓存对象
* @param cacheName 缓存对象名
* @param key 缓存元素名称
* @return
*/
public static Object get(String cacheName, Object key) {
//根据缓存对象名获取缓存管理器中的指定缓存对象
Cache cache = cacheManager.getCache(cacheName);
//根据缓存元素名称获取Cache缓存对象中存储的Element缓存元素
Element element = cache.get(key);
return null == element ? null : element.getValue();
}
public static void remove(String cacheName, Object key) {
Cache cache = cacheManager.getCache(cacheName);
cache.remove(key);
}
}
SessionFactoryUtils:
package com.zengjing.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SessionFactoryUtils {
private static final String
HIBERNATE_CONFIG_FILE="hibernate.cfg.xml";
private static ThreadLocal<Session> threadLocal=
new ThreadLocal<Session>();
//创建数据库的会话工厂
private static SessionFactory sessionFactory;
//读取hibernate核心配置
private static Configuration configuration;
static {
try {
configuration=new Configuration();
configuration.configure(HIBERNATE_CONFIG_FILE);
//创建Session会话工厂
sessionFactory=configuration.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Session openSession() {
Session session = threadLocal.get();
if(null==session) {
session=sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() {
Session session = threadLocal.get();
if(null!=session) {
if(session.isOpen())
session.close();
threadLocal.set(null);
}
}
public static void main(String[] args) {
Session session = SessionFactoryUtils.openSession();
System.out.println("Session状态:"+session.isOpen());
System.out.println("Session会话已打开");
SessionFactoryUtils.closeSession();
System.out.println("Session会话已关闭");
}
}
需要的实体类(book):
package com.zengjing.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Book implements Serializable {
private Integer bookId;
private String bookName;
private Float price;
Set<Category> categories=new HashSet<Category>();
public Set<Category> getCategories() {
return categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]";
}
}
需要的实体类(Category):
package com.zengjing.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Category implements Serializable {
private Integer categoryId;
private String categoryName;
Set<Book> books =new HashSet<Book>();
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
@Override
public String toString() {
return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + ", books=" + books + "]";
}
}
指定的实体映射文件中开启二级缓存,例如我的book开启二级缓存(book.hbm.xml):
usage:缓存模式 region:定义缓存对象的名称Cache
<cache usage="read-only" region="com.zengjing.entity.Book"/>
<?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="com.zengjing.entity.Book" table="t_book_hb">
<cache usage="read-only" region="com.zengjing.entity.Book"/>
<id name="bookId" type="java.lang.Integer" column="book_id">
<generator class="increment"></generator>
</id>
<property name="bookName" type="java.lang.String" column="book_name"/>
<property name="price" type="java.lang.Float" column="price"/>
<!-- 多对多映射关系 -->
<!--
name:一方包含多方的属性对象名称,指向多方
cascade:级联操作 save-update/none/delete/all=delete+save-update
inverse:是否是主控方, false表示对方不是主控方
true表示对方是主控方,由对方来维护中间表
table:表示中间表的名称
-->
<set name="categories"
cascade="save-update"
inverse="false"
table="t_book_category_hb">
<!--
column:指向己方在中间表中的外键字段
-->
<key column="bid"></key>
<!--
class:对方实例完整路径
column:对方在中间表中的外键字段
-->
<many-to-many class="com.zengjing.entity.Category"
column="cid">
</many-to-many>
</set>
</class>
</hibernate-mapping>
bookDao:
package com.zengjing.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.zengjing.entity.Book;
import com.zengjing.util.SessionFactoryUtils;
public class BookDao {
public Book get(Book book) {
Session session = SessionFactoryUtils.openSession();
Transaction ts = session.beginTransaction();
//CRUD
Book b = session.get(Book.class, book.getBookId());
ts.commit();
SessionFactoryUtils.closeSession();
return b;
}
public List<Book> list() {
Session session = SessionFactoryUtils.openSession();
Transaction ts = session.beginTransaction();
//CRUD
Query query = session.createQuery(" from Book ");
query.setCacheRegion("com.zengjing.entity.Book");// 指定缓存策略,名字必须实体类的完整类名!!!
query.setCacheable(true);// 手动开启二级缓存!!!
List<Book> list = query.list();
ts.commit();
SessionFactoryUtils.closeSession();
return list;
}
}
Juint测试:
package com.zengjing.dao;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.zengjing.entity.Book;
public class BookDaoTest {
Book book=null;
BookDao bookDao=new BookDao();
@Before
public void setUp() throws Exception {
book=new Book();
}
//查询单个
@Test
public void test() {
book.setBookId(1);
Book b1 = bookDao.get(book);
System.out.println(b1);
System.out.println("-------------------------------------");
Book b2 = bookDao.get(book);
System.out.println(b2);
}
//查询全部
@Test
public void testAll() {
List<Book> list = bookDao.list();
list.forEach(b->{
System.out.println(b);
});
System.out.println("-------------------------------------");
List<Book> lst = bookDao.list();
lst.forEach(b->{
System.out.println(b);
});
}
}
单个查询结果(我上方测试获取了两次单个查询的数据,但是下方结果SQL语句只查询了一次,说明第二次是从缓存中获取到的):
查询全部结果也是同上的查询SQL只有一次,但是获取数据两次都能获取到,第二次也是从缓存中获取的!