如果數(shù)據(jù)庫(kù)中的數(shù)據(jù)和一級(jí)緩存中的數(shù)據(jù)不一致了胀茵,那mybatis如何做到同步的呢载碌?
mybatis當(dāng)調(diào)用了sqlsession的修改试和、添加讯泣、刪除、commit()阅悍、close()等方法時(shí)就會(huì)清空一級(jí)緩存好渠,
IDEA版本
Build #IU-222.3345.118, built on July 26, 2022
java 環(huán)境
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>
實(shí)例代碼
@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);
}
由圖片可以看出來(lái)晦墙,第二次查詢并沒(méi)有運(yùn)行sql語(yǔ)句
實(shí)例代碼
@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("兩次查詢結(jié)果"+(user==user2));
}
清除一級(jí)緩存,在此查詢運(yùn)行了sql語(yǔ)句