转载自:https://www.jianshu.com/p/b8fa01332cdd
二级缓存的使用:
1.Mybatis配置了全局总开关:全局配置变量参数cacheEnabled=true
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
2.在mapper文件中,配置<cache type=">
或<cache type-ref=">
节点
<cache type="com.example.hello.mybatis.MyBatisRedisCache">
<property name="eviction" value="LRU" />
<property name="flushInterval" value="6000000" />
<property name="size" value="1024" />
<property name="readOnly" value="false" />
</cache>
<cache type=">
是为每个mapper对象生成一个缓存对象
<cache type-ref=">
是为多个mapper对象公用一个缓存对象
3.在具体的select节点中,加上useCache=true
<select id="findById" parameterType="java.lang.String" resultMap="ProductInfoMap" useCache="true">
select * from tb_productInfo
where productInfo_id = #{productId} limit 1
</select>
只有上述三点全部满足才会开启二级缓存
一级缓存和二级缓存的使用顺序
请注意,如果你的MyBatis使用了二级缓存,并且你的Mapper和select语句也配置使用了二级缓存,那么在执行select查询的时候,MyBatis会先从二级缓存中取输入,其次才是一级缓存,即MyBatis查询数据的顺序是:
二级缓存
——> 一级缓存
——> 数据库