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();
    }
原文地址:https://www.cnblogs.com/lyh233/p/12364035.html