mybatis缓存

一级缓存

MyuBatis一级缓存默认开启,是session级别的缓存。当在同一个session范围内执行查询的时候,如果执行相同的查询,那么第二次查询会从缓存中获取数据

@Test
public void testSelectBlogsCacheLevelOne1(){
    SqlSession session = MyBatisUtil.sqlSession();
    BlogsMapper blogsMapper = session.getMapper(BlogsMapper.class);

    Blogs blog1 = blogsMapper.selectByPrimaryKey(1);
    System.out.println("结果已查询"+blog1);
    Blogs blog2 = blogsMapper.selectByPrimaryKey(1);
    System.out.println("结果已查询:从缓存中获取数据"+blog2);

    session.close();
    System.out.println("session关闭");
}

一级缓存被刷新的情况

如果在两次查询中间有增删改的操作,那么MyBatis就会重新刷新清空缓存区,那么下一次查询会重新执行sql语句

@Test
public void testSelectBlogsCacheLevelOne2(){
    SqlSession session = MyBatisUtil.sqlSession();
    BlogsMapper blogsMapper = session.getMapper(BlogsMapper.class);

    Blogs blogs1 = blogsMapper.selectByPrimaryKey(1);
    System.out.println("查询结果:"+blogs1);
    blogs1.setFeatured((byte)0);
    blogsMapper.updateByPrimaryKey(blogs1);
    System.out.println("刷新缓存");

    Blogs blogs2 = blogsMapper.selectByPrimaryKey(1);
    System.out.println("重新执行查询:"+blogs2);

    session.commit();
    session.close();

    System.out.println("session关闭");
}

二级缓存

二级缓存指的是在不同的session范围内,执行相同的数据查询。MyBatis默认二级缓存不开启,所以每次查询将会执行独立的数据库检索过程

@Test
public void testSelectBlogsCacheLevelTwo1(){

    SqlSession session1 = MyBatisUtil.sqlSession();
    BlogsMapper blogsMapper1 = session1.getMapper(BlogsMapper.class);
    Blogs blogs1 = blogsMapper1.selectByPrimaryKey(1);
    System.out.println("查询结果:"+blogs1);
    session1.close();

    SqlSession session2 = MyBatisUtil.sqlSession();
    BlogsMapper blogsMapper2 = session2.getMapper(BlogsMapper.class);
    Blogs blogs2 = blogsMapper2.selectByPrimaryKey(1);
    System.out.println("查询结果:"+blogs2);
    session2.close();
}

开启二级缓存

  1. 在需要开启二级缓存的表的mapper中添加:
<cache  />  
  1. 在实体类中继承序列化接口
public class Blogs implements Serializable {
    ...
}

二级缓存被刷新的情况

跟一级缓存一样,如果两次查询中进行了增删改操作,就会刷新缓存区