22、mybatis学习——mybatis的一级缓存

复制代码
    /*测试一级缓存(本地缓存):sqlSession的缓存级别。一级缓存是一直开启的
     *    与数据库同一次会话期间查询到的数据会放在本地缓存中。
     *    以后如果需要获取相同的数据,直接从缓存中拿,不需要再去查数据库;
     *
     *    一级缓存失效情况:
     *        1、sqlSession不同
     *        2、sqlSession相同,查询条件不同(当前一级缓存中还没有这个数据)
     *        3、sqlSession相同,两次查询之间执行了增删改操作(这次增删改可能对当前的数据有影响)
     *        4、sqlSession相同,手动清除了一级缓存(缓存清空)*/
    @Test
    public void testFirstLevelCache1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student stu1 = studentMapper.getStuById(1);
        Student stu2 = studentMapper.getStuById(1);
        //此时stu2是直接从一级缓存中取出的,不会发出sql语句
        System.out.println(stu1==stu2);
        sqlSession.close();
    }
    
    @Test
    public void testFirstLevelCache2() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student stu1 = studentMapper.getStuById(1);
        studentMapper.updateStu(new Student(2, "李四", new College(1)));
        Student stu2 = studentMapper.getStuById(1);
        //此时中间有增删改操作,会再次发出sql语句
        System.out.println(stu1==stu2);
        sqlSession.close();
    }
复制代码

 

posted @   Arbitrary233  阅读(183)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示