目录
二、开启全局二级缓存之后。默认SQL映射文件是不使用的,还需要在SQL映射文件中配置缓存。
MyBatis框架缓存分类
1、一级缓存
MyBatis框架的一级缓存是基于 PerpetualCache 的 HasMap 本地缓存,默认时 SqlSession 级别的缓存,在 SqlSession 的一个生命周期内有效。当 SqlSession 关闭后的,该 SqlSession 中的所有缓存会被清空。一级缓存默认开启
2、二级缓存
二级缓存是 SqlSessionFactory 级别,作用域大于SqlSession。可被同一个SqlSessionFactory创建的SqlSession 所共享。默认是关闭的
使用二级缓存的方法
一、在MyBatis框架核心配置文件中设置全局开启二级缓存
<settings>
<!-- 开启二级缓存 默认值为true-->
<setting name="cacheEnabled" value="true"/>
</settings>
二、开启全局二级缓存之后。默认SQL映射文件是不使用的,还需要在SQL映射文件中配置缓存。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cn.shity.dao.StorageRecordmapper">
<!-- eviction缓存回收策略
LRU:默认选项,最近最少回收,移除最长不被使用的缓存对象
FIFO:先进先出,按对象进入缓存的顺序来移除它们
SOFT:软引用,移除基于垃圾回收器状态和软引用规则的对象
WEAK:弱引用,更积极第移除基于垃圾回收器状态和弱引用规则的对象
-->
<!-- flushInterval设定缓存刷新间隔(以毫秒为单位) 默认不刷新-->
<!-- size设定缓存最多存放多少个对象 默认是1024 -->
<!-- readOnly 设定缓存数据是否只读 默认是false -->
<cache
eviction="FIFO"
flushInterval="600000"
size="512"
readOnly="true"
/>
</mapper>
三、配置好之后可对个别查询语句进行调整
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cn.shity.dao.StorageRecordmapper">
<!-- eviction缓存回收策略-->
<!-- flushInterval设定缓存刷新间隔(以毫秒为单位) 默认不刷新-->
<!-- size设定缓存最多存放多少个对象 默认是1024 -->
<!-- readOnly 设定缓存数据是否只读 默认是false -->
<cache
eviction="FIFO"
flushInterval="600000"
size="512"
readOnly="true"
/>
<resultMap id="s2" type="StorageRecord">
<id property="id" column="id"/>
<association property="supperlier" javaType="Supperlier">
<id property="sid" column="sid"/>
</association>
</resultMap>
<!-- 使用useCache进行设置调整 -->
<select id="all" resultMap="s2" parameterType="StorageRecord" useCache="false">
SELECT * FROM t_storage_record
INNER JOIN t_supplier ON(t_supplier.sid=t_storage_record.supplierId)
<where>
<if test="map !=null">
and supplierId in
<foreach collection="map" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</where>
</select>
</mapper>