一级缓存

Mybatis自带默认的,是SqlSession级别的,也就是同一个SqlSession内执行相同select语句的时候,不再去查询数据库,而是从Mybatis内部的缓存内存中获取数据。

    @Test
    public void queryUserById(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.queryUserById(3);
        //sqlSession.commit();
        //sqlSession.close();        
        User user1=userMapper.queryUserById(3);
        System.out.println(user);
        System.out.println(user1);
        sqlSession.close();
    }

日志中记录只有一条sql语句,说明第二次查询时,直接从缓存中获取数据。

select * from userinfo where userid=? 

一级缓存失效的时机:

  • sqlSession关闭
  • sqlSession提交事务(可能是一个增删改的动作,需要更新缓存,那这个时候Mybatis就会把已有的缓存给清理掉)。

二级缓存

Mybatis二级缓存是Mapper.xml级别的,不考虑是不是同一个sqlSession,只考虑是不是同一个Mapper的同一个sql语句。

开启缓存

  1. Mybatis全局配置文件中添加
    <!--设置开启二级缓存-->
    <setting name="cacheEnabled" value="true"/>
  2. 具体mapper.xml启用二级缓存
    <!--具体mapper.xml启用二级缓存-->
    <cache/>
  3. POJO实现可序列化
    //POJO实现可序列化
    public class User implements Serializable{

Mybatis二级缓存弊端:同步不及时。

 posted on 2019-08-14 21:44  会飞的金鱼  阅读(106)  评论(0)    收藏  举报