一级缓存:同一个sqlSession多次查询同一个值,就会使用一级缓存。session就是一级缓存。mybatis默认开启一级缓存。大家了解即可。
二级缓存:同一个mapper.xml文件就是二级缓存
PersonMapper mapper = session.getMapper(PersonMapper.class);
PersonMapper mapper1 = session1.getMapper(PersonMapper.class);
这里的mapper和mapper1共享二级缓存
二级缓存需手动开始:
<1>在cofig.xml文件中配置
<settings>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<2>在mapper.xml文件中声明
<!-- 声明二级缓存-->
<cache/>
<3>序列化目标类:需要将使用到的类序列化,就是实现Serializable接口(因为二级缓存在硬盘上)。
当sqlSession.close时,一级缓存的中的数据才会转存到二级缓存中。
二级缓存的关闭:
<select id="selectById" resultType="Person" parameterType="int" useCache="false">
select * from Person where id = #{id}
</select>
刷新缓存
<select id="selectById" resultType="Person" parameterType="int" FlushCache="false">
select * from Person where id = #{id}
</select>
注:一级二级缓存,都是在执行session.commit()时清除,防止缓存数据和数据库数据不一致,导致错读。