一、概述
MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便地配置和定制。MyBatis中的缓存机制可以极大的提升查询效率。
MyBatis系统中默认定义了两级缓存。一级缓存和二级缓存。
1、默认情况下,只有一级缓存(SqlSession级别的缓存,也称为本地缓存)开启。
2、二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
3、为了提高扩展性。MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。
二、一级缓存
一级缓存(本地缓存):sqlSession级别的缓存。与数据库同一次会话期间查询到的数据会放在本地缓存中。以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库。
一级缓存是一直开启的,当 Session flush 或 close 后,该Session 中的所有 Cache 将被清空。本地缓存不能被关闭,但可以调用 clearCache()来清空本地缓存,或者改变缓存的作用域。在mybatis3.1之后,可以配置本地缓存的作用域。在 mybatis.xml 中配置:
如下代码所示,如果查找了两次id为3的员工,MyBatis到底会怎么做呢?
@Test
public void test01() throws IOException {
// 1、获取sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
// 2、获取sqlSession对象
SqlSession openSession = sqlSessionFactory.openSession();
try {
// 3、获取接口的实现类对象
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(3);
System.out.println(employee);
Employee employee1 = mapper.getEmpById(3);
System.out.println(employee1);
} finally {
openSession.close();
}
}
Opening JDBC Connection
Checked out connection 1287712235 from pool.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cc0edeb]
==> Preparing: select id,last_name,email,gender from tbl_employee where id = ?
==> Parameters: 3(Integer)
<== Columns: id, last_name, email, gender
<== Row: 3, jerry4, 223@163.com, 1
<== Total: 1
Employee [id=3, lastName=jerry4, email=jerry4, gender=1]
Employee [id=3, lastName=jerry4, email=jerry4, gender=1]
可以看到,MyBatis只发送了一个sql语句,第二次查询是直接从缓存中获取的。
注:一级缓存失效的四种情况
一级缓存失效的四种情况,即没有使用到当前一级缓存的情况,还需要再向数据库发出查询。
1、sqlSession不同。不同的SqlSession对应不同的一级缓存。
2、同一个SqlSession但是查询条件不同(当前一级缓存中还没有这个数据)。
3、同一个SqlSession两次查询期间执行了任何一次增删改操作。由于这次增删改可能对当前数据有影响,所以需要重新向数据库发出查询。
4、同一个SqlSession两次查询期间手动清空了缓存。openSession.clearCache();
三、二级缓存
二级缓存(全局缓存):基于namespace级别的缓存,一个namespace对应一个二级缓存。二级缓存默认不开启,需要手动配置。 MyBatis提供二级缓存的接口以及实现,缓存实现要求:POJO实现Serializable接口。二级缓存在 SqlSession 关闭或提交之后才会生效。
使用步骤:
1)、在MyBaits全局配置文件中开启全局二级缓存配置;
<setting name="cacheEnabled" value="true"/>
2)、去mapper.xml中配置使用二级缓存:
<mapper namespace="com.mybatis.dao.EmployeeMapper">
<!--使用二级缓存-->
<cache></cache>
可以在cache标签中配置一些属性,cache标签中的属性如下所示:
eviction:缓存的回收策略:
LRU – 最近最少使用的:移除最长时间不被使用的对象。
FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
默认的是 LRU。
flushInterval:缓存刷新间隔。缓存多长时间清空一次,设置一个毫秒值,默认不清空。
readOnly:是否只读:
true:只读;**mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。**mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户。不安全,但速度快。
false:非只读:mybatis觉得获取的数据可能会被修改时,mybatis会利用序列化&反序列的技术克隆一份新的数据给用户。安全,但速度慢。
size:缓存存放多少元素;
type=”“:指定自定义缓存的全类名;实现Cache接口即可;
3)、在我们的POJO中实现序列化接口;
public class Employee implements Serializable{}
public class Department implements Serializable{}
测试代码如下:
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);
Employee emp01 = mapper.getEmpById(3);
System.out.println(emp01);
openSession.close();
//第二次查询是从二级缓存中拿到的数据,并没有发送新的sql
Employee emp02 = mapper2.getEmpById(3);
System.out.println(emp02);
openSession2.close();
接下来看看测试结果:
Opening JDBC Connection
Checked out connection 1287712235 from pool.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cc0edeb]
==> Preparing: select id,last_name,email,gender from tbl_employee where id = ?
==> Parameters: 3(Integer)
<== Columns: id, last_name, email, gender
<== Row: 3, jerry4, 223@163.com, 1
<== Total: 1
Employee [id=3, lastName=jerry4, email=jerry4, gender=1]
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cc0edeb]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cc0edeb]
Returned connection 1287712235 to pool.
Cache Hit Ratio [com.mybatis.dao.EmployeeMapper]: 0.5
Employee [id=3, lastName=jerry4, email=jerry4, gender=1]
不难看出,只执行了一次SQL,第二次的记录是从缓存Cache Hit Ratio
中取出的。
工作机制:
1、一个会话,查询一条数据,这个数据就会被放在当前会话的一级缓存中;
2、如果会话关闭,一级缓存中的数据会被保存到二级缓存中;新的会话查询信息,就可以参照二级缓存中的内容。
3、不同namespace查出的数据会放在自己对应的缓存中(map)。
四、和缓存有关的设置或属性
一、设置全局配置文件中的cacheEnabled=true
为false,可以关闭缓存。且关闭的是二级缓存,一级缓存一直可用的。
二、每个select标签都有useCache="true"
改为false之后将不使用缓存(一级缓存依然使用,二级缓存不使用)。
三、每个增删改标签的:flushCache="true"
(默认为true),一级二级都会清除,所以增删改执行完成后就会清楚缓存;
测试:flushCache=”true”:一级缓存就清空了;二级也会被清除;
查询标签:flushCache="false"
(默认为false),如果flushCache=true
每次查询之后都会清空缓存。
四、sqlSession.clearCache()
只是清楚当前session的一级缓存。
五、localCacheScope:本地缓存作用域:(一级缓存SESSION);当前会话的所有数据保存在会话缓存中;STATEMENT:可以禁用一级缓存。一般不用设置。
五、第三方缓存整合
由于MyBaits不是专业做缓存的,所以MyBatis定义了Cache接口方便我们进行自定义扩展。如整合EhCache ,或者Redis。
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
下面以EhCache为例,看一下MyBaits与第三方缓存整合的步骤:
https://github.com/mybatis/ehcache-cache
http://www.mybatis.org/ehcache-cache/
第三方缓存整合:
1)、开启mybatis的二级缓存
<settings>
<!--开启驼峰命名-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--开启SQL日志-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
2)、导入与第三方缓存整合的适配包
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
3)、在类路径下添加ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!-- 磁盘保存路径 -->
<diskStore path="D:\mybaits\ehcache" />
<defaultCache
maxElementsInMemory="10000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
<!--
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
-->
4)、在mapper.xml中使用自定义缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
<mapper namespace="com.mybatis.dao.EmployeeMapper">
<!--使用EhcacheCache缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
5)测试结果
Opening JDBC Connection
Checked out connection 1715998167 from pool.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@66480dd7]
==> Preparing: select id,last_name,email,gender from tbl_employee where id = ?
==> Parameters: 3(Integer)
<== Columns: id, last_name, email, gender
<== Row: 3, jerry4, 223@163.com, 1
<== Total: 1
Employee [id=3, lastName=jerry4, email=jerry4, gender=1]
DEBUG 03-13 18:07:49,461 put added 0 on heap (Segment.java:425)
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@66480dd7]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@66480dd7]
Returned connection 1715998167 to pool.
Cache Hit Ratio [com.mybatis.dao.EmployeeMapper]: 0.5
Employee [id=3, lastName=jerry4, email=jerry4, gender=1]
注:在整合EhCache的时候遇到的错误
一、
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
出现这个错误的原因是sl4j和log4j的不兼容导致的,加入slf4j-log4j和log4j两个jar包即可。
二、
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
出现这个错误的原因是少了logj的配置文件,在工程中加入log4j.xml即可。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>