栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis缓存的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis缓存的使用

MyBatis 中的缓存就是说 MyBatis 在执行一次SQL查询或者SQL更新之后,这条SQL语句并不会消失,而是被MyBatis 缓存起来,当再次执行相同SQL语句的时候,就会直接从缓存中进行提取,而不是再次执行SQL命令。

mybatis的缓存机制有两级:

(1)一级缓存:一级缓存mybatsi已经为我们自动开启,不用我们手动操作,而且我们是关闭不了的!!但是我们可以手动清除缓存。

 @Test                  
    public void test01(){  //mybatis的缓存 一级缓存  在二次系统的查询之间 手动清空缓存
                           //一级缓存失效  1.手动清空缓存 2.手动提交事务 3.做增删改操作
        SqlSession sqlSession1 = factory.openSession();
        SqlSession sqlSession2 = factory.openSession();

        StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
        StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);

        List students = mapper1.selectAll();
        students.forEach(student -> System.out.println("student = " + student));

        //手动清空缓存

        System.out.println("------------------------------------------------------");
        System.out.println("------------------------------------------------------");

        students  = mapper2.selectAll();
        students.forEach(student -> System.out.println("student = " + student));
    }

一级缓存失效的情况:

1.不同的SqlSession对应不同的缓存
2.同一个SqlSession但是查询条件不同
3.同一个SqlSession执行两次相同查询之间做了增删改的操作
4.同一个SqlSession执行两次相同查询之间手动清空缓存
5.手动提交事务

(2)二级缓存:二级缓存需要我们手动开启,需要引入cacheEnabled。


        
        
        
    

在具体需要二级缓存的mapeer映射文件中开启二级缓存,值需要在相应的映射文件中添加一个cache标签即可

在相应的映射文件中开启二级缓存


 
@Test
    public void test04(){  //mybatis 的缓存 二级缓存
        //在二次系统的查询之间 手动清空缓存
        SqlSession sqlSession1 = factory.openSession();
        SqlSession sqlSession2 = factory.openSession();

        StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
        StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);

        List students = mapper1.selectAll();
        students.forEach(student -> System.out.println("student = " + student));

        //手动提交事务  将数据的一级缓存 写入二级缓存
        //sqlSession1.commit();
        sqlSession1.close();     //close() 写入二级缓存

        System.out.println("-------------------------------------------------------");
        System.out.println("-------------------------------------------------------");

        students  = mapper2.selectAll();
        students.forEach(student -> System.out.println("student = " + student));
    }

二级缓存失效的条件:

1.在两次查询之间进行了任意的增删改操作,一级二级缓存同时失效

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985763.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号