之前我们介绍过映射器与XML配置职责分离,本篇我们在此基础上介绍Mybatis中二级缓存的使用。
如果您对映射器与XML配置职责分离不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis 映射器与XML配置职责分离https://blog.csdn.net/m1729339749/article/details/133196679
一、数据准备
这里我们直接使用脚本初始化数据库中的数据
-- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建用户表
CREATE TABLE IF NOT EXISTS T_USER(
ID INT PRIMARY KEY,
USERNAME VARCHAR(32) NOT NULL,
AGE INT NOT NULL
);
-- 插入用户数据
INSERT INTO T_USER(ID, USERNAME, AGE)
VALUES(1, '张三', 20),(2, '李四', 22),(3, '王五', 24);
创建了一个名称为demo的数据库;并在库里创建了名称为T_USER的用户表并向表中插入了数据
二、创建实体类
在cn.horse.demo下创建UserInfo、UserInfoQuery类,另外需要特别注意缓存的对象类型必须实现Serializable接口
UserInfo类:
package cn.horse.demo;
import java.io.Serializable;
public class UserInfo implements Serializable {
private static final long serialVersionUID = 9213975268411777481L;
private Integer id;
private String name;
private Integer age;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('{');
stringBuilder.append("id: " + this.id);
stringBuilder.append(", ");
stringBuilder.append("name: " + this.name);
stringBuilder.append(", ");
stringBuilder.append("age: " + this.age);
stringBuilder.append('}');
return stringBuilder.toString();
}
}
UserInfoQuery类:
package cn.horse.demo;
public class UserInfoQuery {
private Integer startAge;
private Integer endAge;
public void setStartAge(Integer startAge) {
this.startAge = startAge;
}
public Integer getStartAge() {
return startAge;
}
public void setEndAge(Integer endAge) {
this.endAge = endAge;
}
public Integer getEndAge() {
return endAge;
}
}
三、创建映射器、Mapper配置
在cn.horse.demo下创建UserInfoMapper接口
UserInfoMapper接口:
package cn.horse.demo;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserInfoMapper {
List<UserInfo> find(@Param("query") UserInfoQuery query);
Integer insert(@Param("userInfoList") List<UserInfo> userInfoList);
Integer update(@Param("userInfoList") List<UserInfo> userInfoList);
Integer delete(@Param("idList") List<Integer> idList);
}
在resources下创建cn/horse/demo目录,并在此目录下创建UserInfoMapper.xml配置文件
UserInfoMapper.xml配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.UserInfoMapper">
<cache />
<resultMap id="userInfoMap" type="cn.horse.demo.UserInfo">
<result column="ID" property="id" />
<result column="USERNAME" property="name"/>
<result column="AGE" property="age"/>
</resultMap>
<select id="find" parameterType="cn.horse.demo.UserInfoQuery" resultMap="userInfoMap">
SELECT
ID,
USERNAME,
AGE
FROM T_USER
<where>
<if test="null != query.startAge">
AND AGE >= #{query.startAge}
</if>
<if test="null != query.endAge">
AND AGE <= #{query.endAge}
</if>
</where>
</select>
<insert id="insert">
INSERT INTO T_USER(ID,
USERNAME,
AGE)
VALUES
<foreach collection="userInfoList" item="userInfo" separator=",">
(#{userInfo.id}, #{userInfo.name}, #{userInfo.age})
</foreach>
</insert>
<update id="update">
<foreach collection="userInfoList" item="userInfo" separator=";" close=";">
UPDATE T_USER
<set>
<if test="null != userInfo.name and '' != userInfo.name">
USERNAME = #{userInfo.name},
</if>
<if test="null != userInfo.age">
AGE = #{userInfo.age},
</if>
</set>
WHERE ID = #{userInfo.id}
</foreach>
</update>
<delete id="delete">
DELETE FROM T_USER
<where>
ID IN
<foreach collection="idList" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</delete>
</mapper>
注意:cache标签代表在此命名空间下使用二级缓存
四、引入配置文件
在resources下新建mybatis-config.xml配置文件,并引入UserInfoMapper映射器。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="JDK_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true"/>
<property name="username" value="root"/>
<property name="password" value="horse"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="cn.horse.demo.UserInfoMapper" />
</mappers>
</configuration>
这里我们使用mapper引入映射器,只需要设置class属性为UserInfoMapper接口的全限类名。
五、启动程序配置
1、会话工具类
在cn.horse.demo包下新建SqlSessionUtils工具类
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.Objects;
public class SqlSessionUtils {
private static final SqlSessionFactory sqlSessionFactory;
static {
// 读取mybatis配置文件
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
// 根据配置创建SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
}
/**
* 开启会话
* @return
*/
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
/**
* 关闭会话
* @param sqlSession
*/
public static void closeSession(SqlSession sqlSession) {
if(Objects.nonNull(sqlSession)) {
sqlSession.close();
}
}
}
2、JDK 日志系统配置
在resources的目录下新建logging.properties配置文件
handlers=java.util.logging.ConsoleHandler
.level=INFO
cn.horse.demo.UserInfoMapper.level=FINER
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tT.%1$tL %4$s %3$s - %5$s%6$s%n
在cn.horse.demo下创建JdkLogConfig类
JdkLogConfig类:
package cn.horse.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
public class JdkLogConfig {
public JdkLogConfig() {
try {
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
LogManager.getLogManager().readConfiguration(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
3、启动程序配置
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
private static final Logger LOGGER;
static {
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
LOGGER = Logger.getLogger("cn.horse.demo.Main");
}
public static void main(String[] args) throws InterruptedException {
}
private static void batchInsert(final List<UserInfo> userInfoList) {
LOGGER.log(Level.FINER, "--------------- 插入 ----------------");
execute((UserInfoMapper userInfoMapper) -> {
Integer total = userInfoMapper.insert(userInfoList);
LOGGER.log(Level.INFO, "插入条数: " + total);
});
}
private static void batchUpdate(final List<UserInfo> userInfoList) {
LOGGER.log(Level.FINER, "--------------- 更新 ----------------");
execute((UserInfoMapper userInfoMapper) -> {
Integer total = userInfoMapper.update(userInfoList);
LOGGER.log(Level.INFO, "更新条数: " + total);
});
}
private static void batchDelete(final List<Integer> idList) {
LOGGER.log(Level.FINER, "--------------- 删除 ----------------");
execute((UserInfoMapper userInfoMapper) -> {
Integer total = userInfoMapper.delete(idList);
LOGGER.log(Level.INFO, "删除条数: " + total);
});
}
private static void selectGreaterThan(Integer age) {
LOGGER.log(Level.FINER, "--------------- 查询 ----------------");
execute((UserInfoMapper userInfoMapper) -> {
UserInfoQuery query = new UserInfoQuery();
query.setStartAge(age);
List<UserInfo> userInfoList = userInfoMapper.find(query);
for (UserInfo userInfo: userInfoList) {
LOGGER.log(Level.INFO, userInfo.toString());
}
});
}
private static void execute(Consumer<UserInfoMapper> function) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
function.accept(sqlSession.getMapper(UserInfoMapper.class));
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
}
execute方法用于执行操作,方法中使用sqlSession.getMapper方法获取映射器对象,然后将映射器对象具体的执行操作委托给了Consumer对象。
六、何时存取二级缓存
// 查询
selectGreaterThan(20);
// 查询
selectGreaterThan(20);
执行后的结果如下:
从打印的SQL执行记录可以看出,第二次查询时使用到了缓存,说明在第一次查询时就写入了缓存,其实是select标签中的SQL语句执行时会使用缓存或者对查询结果进行缓存。
七、何时过期二级缓存
1、insert标签
// 查询
selectGreaterThan(20);
// 插入
List<UserInfo> insertUserInfoList = new ArrayList<>();
UserInfo insertUserInfo1 = new UserInfo();
insertUserInfo1.setId(5);
insertUserInfo1.setName("王五1");
insertUserInfo1.setAge(5);
insertUserInfoList.add(insertUserInfo1);
UserInfo insertUserInfo2 = new UserInfo();
insertUserInfo2.setId(6);
insertUserInfo2.setName("王五2");
insertUserInfo2.setAge(6);
insertUserInfoList.add(insertUserInfo2);
batchInsert(insertUserInfoList);
// 查询
selectGreaterThan(20);
执行后的结果如下:
从打印的SQL执行记录可以看出,第二次查询时未使用缓存,说明在第一次查询时写入的缓存过期了,其实是insert标签中的SQL语句执行后会使缓存过期。
2、update标签
// 查询
selectGreaterThan(20);
// 更新
List<UserInfo> updateUserInfoList = new ArrayList<>();
UserInfo updateUserInfo1 = new UserInfo();
updateUserInfo1.setId(5);
updateUserInfo1.setName("王五11");
updateUserInfoList.add(updateUserInfo1);
UserInfo updateUserInfo2 = new UserInfo();
updateUserInfo2.setId(6);
updateUserInfo2.setAge(26);
updateUserInfoList.add(updateUserInfo2);
batchUpdate(updateUserInfoList);
// 查询
selectGreaterThan(20);
执行后的结果如下:
从打印的SQL执行记录可以看出,第二次查询时未使用缓存,说明在第一次查询时写入的缓存过期了,其实是update标签中的SQL语句执行后会使缓存过期。
3、delete标签
// 查询
selectGreaterThan(20);
// 删除
batchDelete(Arrays.asList(5, 6));
// 查询
selectGreaterThan(20);
执行后的结果如下:
从打印的SQL执行记录可以看出,第二次查询时未使用缓存,说明在第一次查询时写入的缓存过期了,其实是delete标签中的SQL语句执行后会使缓存过期。
八、可能出现的问题
2023-09-19 17:27:58.570 较详细 cn.horse.demo.Main - --------------- 查询 ----------------
2023-09-19 17:27:58.850 详细 cn.horse.demo.UserInfoMapper - Cache Hit Ratio [cn.horse.demo.UserInfoMapper]: 0.0
2023-09-19 17:27:59.009 详细 cn.horse.demo.UserInfoMapper.find - ==> Preparing: SELECT ID, USERNAME, AGE FROM T_USER WHERE AGE >= ?
2023-09-19 17:27:59.032 详细 cn.horse.demo.UserInfoMapper.find - ==> Parameters: 20(Integer)
2023-09-19 17:27:59.039 较详细 cn.horse.demo.UserInfoMapper.find - <== Columns: ID, USERNAME, AGE
2023-09-19 17:27:59.039 较详细 cn.horse.demo.UserInfoMapper.find - <== Row: 1, 张三, 20
2023-09-19 17:27:59.040 较详细 cn.horse.demo.UserInfoMapper.find - <== Row: 2, 李四, 22
2023-09-19 17:27:59.041 较详细 cn.horse.demo.UserInfoMapper.find - <== Row: 3, 王五, 24
2023-09-19 17:27:59.041 详细 cn.horse.demo.UserInfoMapper.find - <== Total: 3
2023-09-19 17:27:59.042 信息 cn.horse.demo.Main - {id: 1, name: 张三, age: 20}
2023-09-19 17:27:59.043 信息 cn.horse.demo.Main - {id: 2, name: 李四, age: 22}
2023-09-19 17:27:59.043 信息 cn.horse.demo.Main - {id: 3, name: 王五, age: 24}
Exception in thread "main" org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: cn.horse.demo.UserInfo
at org.apache.ibatis.cache.decorators.SerializedCache.serialize(SerializedCache.java:102)
at org.apache.ibatis.cache.decorators.SerializedCache.putObject(SerializedCache.java:56)
at org.apache.ibatis.cache.decorators.LoggingCache.putObject(LoggingCache.java:51)
at org.apache.ibatis.cache.decorators.SynchronizedCache.putObject(SynchronizedCache.java:45)
at org.apache.ibatis.cache.decorators.TransactionalCache.flushPendingEntries(TransactionalCache.java:122)
at org.apache.ibatis.cache.decorators.TransactionalCache.commit(TransactionalCache.java:105)
at org.apache.ibatis.cache.TransactionalCacheManager.commit(TransactionalCacheManager.java:44)
at org.apache.ibatis.executor.CachingExecutor.close(CachingExecutor.java:61)
at org.apache.ibatis.session.defaults.DefaultSqlSession.close(DefaultSqlSession.java:264)
at cn.horse.demo.SqlSessionUtils.closeSession(SqlSessionUtils.java:35)
at cn.horse.demo.Main.execute(Main.java:120)
at cn.horse.demo.Main.selectLessThan(Main.java:103)
at cn.horse.demo.Main.main(Main.java:25)
Caused by: java.io.NotSerializableException: cn.horse.demo.UserInfo
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.ArrayList.writeObject(ArrayList.java:768)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1154)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at org.apache.ibatis.cache.decorators.SerializedCache.serialize(SerializedCache.java:97)
从日志中可以看出,出现问题的原因是缓存的对象类型未实现Serializable接口;只需要将缓存的对象类型实现Serializable接口即可解决。