本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一级缓存
默认开启有一级缓存,当用Sql查询过相同的数据后是直接从缓存里面调用,而不会在重新查询一次
一级缓存作用域是sqlsession级别的,同一个sqlsession中执行相同的sql查询(相同的sql和参数),第一次会去查询数据库并写到缓存中,第二次从一级缓存中取。
System.out.println(mapper.getEmpByid(3));
System.out.println(mapper.getEmpByid(3));
何时清空
一级缓存时执行commit,close,增删改等操作,就会清空当前的一级缓存
失效的情况
不同的SqlSession对应不同的一级缓存 同一个SqlSession对应的查询情况不同 同一个SqlSession两次查询了期间执行了一次增删改操作 同一个SqlSession中手动清空缓存
SqlSeesion.clearCache();
二级缓存
在映射文件中设置标签
<cache></cache>
什么时候保存
在关闭SqlSession或提交SqlSession查询的数据会保存二级缓存中
查询的数据所转换的类型必须实现序列化接口
public class Teacher implements Serializable{
}
失效情况
使用了增删改就会失效
二级缓存相关引用
MyBatis添加第三方缓存EHCache
添加到pom.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:\csdn\ehcache"/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
配置文件信息
创建配置文件
文件名必须叫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:\"/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
报红的地方不需要管
设计二级缓存类型
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
加入logback日志
名字一定要是logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别 -->
<logger name="com.csdn.mapper" level="DEBUG"/>
</configuration>
输出
磁盘保存信息
查询数据越多时候也会有相对应的内容