【MyBatis】MyBatis 一级缓存

2022-12-13  本文已影响0人  baihualinxin

如果数据库中的数据和一级缓存中的数据不一致了,那mybatis如何做到同步的呢?
mybatis当调用了sqlsession的修改、添加、删除、commit()、close()等方法时就会清空一级缓存,\color{green}{所以当我们数据库的数据发生更改的时候,它会清空缓存中的数据然后重新发起查询}

\color{red}{在最新的java环境中MyBatis已经做了更新框架,修改过后直接放入缓存中了}
IDEA版本

Build #IU-222.3345.118, built on July 26, 2022

java 环境

OpenJDK version 19.0.1

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>day04_eesy_02cache</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

实例代码

    @Test
    public void testClearCache(){
        User user1 = userDao.findById(41);
        System.out.println(user1);
        user1.setUsername("update user book");
        user1.setAddress("book this book");
        userDao.updateUser(user1);
        User user2 = userDao.findById(41);
        System.out.println(user2);
        System.out.println(user1==user2);
    }
730B556E-635D-4255-BB0E-2E8B3C42E10B.png

由图片可以看出来,第二次查询并没有运行sql语句

实例代码

  @Test
    public void testClearCache(){
        User user = userDao.findById(41);
        System.out.println(user);
        user.setUsername("update user cache");
        user.setAddress("cache this cache");
        userDao.updateUser(user);
        sqlSession.clearCache();
        sqlSession=factory.openSession();
        User user2 = userDao.findById(41);
        System.out.println(user2);
        System.out.println("两次查询结果"+(user==user2));
    }
463FBF6C-0E5E-42BD-A66D-55B3FDA6952B.png

清除一级缓存,在此查询运行了sql语句

上一篇下一篇

猜你喜欢

热点阅读