Springboot + Mybatis-Plus开启二级缓存

发布于:2022-07-26 ⋅ 阅读:(569) ⋅ 点赞:(0)

目录

一级缓存和二级缓存的区别

一级缓存

二级缓存

开启 Mybatis-Plus 二级缓存(可配置)

Mapper.java 配置

Mapper.xml 配置

实体类配置


一级缓存和二级缓存的区别

一级缓存

一级缓存 Mybatis 的一级缓存是指 SQLSession,一级缓存的作用域是 SQlSession , Mabits 默认开启一级缓存。 在同一个SqlSession中,执行相同的SQL查询时;第一次会去查询数据库,并写在缓存中,第二次会直接从缓存中取。 当执行SQL时候两次查询中间发生了增删改的操作,则SQLSession的缓存会被清空。

每次查询会先去缓存中找,如果找不到,再去数据库查询,然后把结果写到缓存中。 Mybatis的内部缓存使用一个HashMap,key为hashcode+statementId+sql语句。Value为查询出来的结果集映射成的java对象。 SqlSession执行insert、update、delete等操作commit后会清空该SQLSession缓存。

二级缓存

二级缓存 二级缓存是 mapper 级别的,Mybatis默认是没有开启二级缓存的。 第一次调用mapper下的SQL去查询用户的信息,查询到的信息会存放到该 mapper 对应的二级缓存区域。 第二次调用 namespace 下的 mapper 映射文件中,相同的sql去查询用户信息,会去对应的二级缓存内取结果。

开启 Mybatis-Plus 二级缓存(可配置)

mybatis-plus:
  type-aliases-package: com.xxx.*.model.entity
  mapper-locations: classpath*:mapper/*Mapper.xml
  global-config:
    banner: false
  configuration:
    # 无论是否开启,二级缓存都生效,不知道什么原因
    cache-enabled: true

Mapper.java 配置

/**
* 添加 @CacheNamespace
*/
@CacheNamespace
public interface UserMapper extends BaseMapper<User> {
    
    
}

Mapper.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.xxx.mapper.UserMapper">
    <!--  配置 cache-ref,并配置 namespace -->
    <cache-ref namespace="com.xxx.xxx.mapper.UserMapper"/>
</mapper>

实体类配置

/**
 * 实体类必须序列化(实现 Serializable)
 */
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 20220714091937L;

}

网站公告

今日签到

点亮在社区的每一天
去签到