Mybatis学习笔记

131 阅读10分钟

1.简介

1.1什么是 MyBatis?

  • MyBatis 是一款优秀的持久层框架。

  • 它支持自定义 SQL、存储过程以及高级映射。

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

  • MyBatis可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.2如何获取Mybits

  • Maven 仓库
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.2</version>
</dependency>

1.3 持久化

数据持久化

  • 将程序的数据在持久化状态和瞬时状态转化的过程

2.第一个Mybatis程序

  • 思路 : 搭建环境->导入Mybatis->编写代码->测试

2.1 搭建环境

  • 1.创建数据库

image-20220302155621820

  • 2.依赖引入
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.github.jaspercloud</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.24</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        
    </dependencies>

2.2 创建一个子模块

mybatis-01

image-20220303150653175

  • 编写Mybatis的核心配置文件

​ XML 配置文件中包含了对 MyBatis系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)。

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库驱动-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--数据库连接,加对数据库的配置-->
                <!--useUnicode=true&amp;characterEncoding=UTF-8用于使数据库显示中文-->
                <property name="url" value
                        ="jdbc:mysql://localhost:3306/mybatis?useSSl=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <!--帐号,密码-->
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
  • 编写Mybatis的工具类
public class MybatisUtils {

// 从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。
// 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。
    public static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

2.3 编写代码

  • 实体类

  • Dao类

public interface UserDao {
//    查询语句
    List<User> getUserList();
}
  • 接口实现类,有原来的impl转换为mapper配置文件
<?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">
<!--命名空间->绑定到Dao/Mapper的接口-->
<mapper namespace="com.gui.dao.UserDao">
<!--    select查询语句,resultType是返回的结果集-->
    <select id="getUserList" resultType="com.gui.pojo.User">
        select * from mybatis.user 
    </select>
</mapper>

2.4 测试(maven资源过滤问题)

public class UserDaoTest {
    @Test
    public void test(){
        //        获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
//        执行
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }

            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
}

image-20220303162635030

  • 出现的错误1 : 创建sqlSession失败,找不到xml文件

image-20220303161615979

在文件目录中有xml文件,但是由于maven的资源过滤问题,导致在target中无法生成相对于的文件

image-20220303161600198

解决方案:

由于Maven的约定大于配置,之后我们写的配置文件可以会出现无法导出的问题,解决方案就是添加资源过滤

<build>       
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
</build>
  • 显示结果

image-20220303162319832

3.增删改查的实现

  • namespace : 命名空间,要绑定的Mapper要和接口一致

  • select : 选择、查询语句

    • id :就是对应的namespace的接口方法名
    • resultType :就是结果返回值类型
  • 注意的是,增删改需要提交事务commit,对象中的属性直接可以取出来

<?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">
<!--命名空间->绑定到Dao/Mapper的接口-->
<mapper namespace="com.gui.dao.UserMapper">
<!--    select查询语句-->
    <select id="getUserList" resultType="com.gui.pojo.User">
        select * from mybatis.user
    </select>

<!--    查询byId-->
    <select id="getUserById" resultType="com.gui.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>

<!--    添加-->
    <insert id="addUser" parameterType="com.gui.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>

<!--    修改-->
    <update id="updateUser" parameterType="com.gui.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>

<!--    删除-->
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
</mapper>

3.1使用Map进行传参

image-20220304152922171

@Test
    public void Test(){
        Map<String ,Object> map = new HashMap<>();
        map.put("userid",5);
        map.put("username","你好Map");
        map.put("userpwd","23425");
        int i = mapper.addUserByMap(map);
        
        sqlSession.commit();
        sqlSession.close();
    }
<!--    添加2ByMap-->
<insert id="addUserByMap" parameterType="map">
    insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{userpwd})
</insert>

3.2模糊查询拓展

  • 在java层面使用:传递通配符
List<User> users = mapper.getUserLike("%王%");
  • 在sql层面使用:通配符拼接
<!--    查询byId-->
    <select id="getUserById" resultType="com.gui.pojo.User" parameterType="int">
        select * from mybatis.user where id = "%"#{id}"%"
    </select>

4.配置解析

###4.1核心配置文件

<!--核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value
                        ="jdbc:mysql://localhost:3306/mybatis?useSSl=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/gui/dao/UserMapper.xml"/>
    </mappers>
</configuration>
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

    configuration(配置)
        properties(属性)
        settings(设置)
        typeAliases(类型别名)
        typeHandlers(类型处理器)
        objectFactory(对象工厂)
        plugins(插件)
        environments(环境配置)
            environment(环境变量)
                transactionManager(事务管理器)
                dataSource(数据源)
        databaseIdProvider(数据库厂商标识)
        mappers(映射器)

4.2环境配置

image-20220304194042201

  • transactionManager(事务管理器)

image-20220304193514402

  • dataSource (数据源)

image-20220304193348604

4.3 属性

  • 编写配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
  • 在核心配置文件中引入,必须放在最上面
<!--核心配置文件-->
<configuration>
<!--引入外部配置文件-->
    <properties resource="db.properties"></properties>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/gui/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4.4类型别名

image-20220304195054215

  • 第一种:适用于少的
<!--起别名-->
    <typeAliases>
        <typeAlias alias="User" type="com.gui.pojo.User"></typeAlias>
    </typeAliases>
  • 第二种,扫描包 ,适用于多的

每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。比如 domain.blog.Author 的别名为 author;若有注解,则别名为其注解值。

@Alias("author")
public class Author {
    ...
}
<typeAliases>
    <package name="com.gui.pojo"/>
</typeAliases>
  • 下面是一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。
别名映射的类型
_bytebyte
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal
objectObject
mapMap
hashmapHashMap
listList
arraylistArrayList
collectionCollection
iteratorIterator

4.4 设置(不重要)

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
mapUnderscoreToCamelCase是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。true | falseFalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J(deprecated since 3.5.9) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置

4.5映射器说明

既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等。例如: 
  • 在使用resource时,xml文件可以随便放置
  • 在使用class时,xml文件必须和接口同名,并且要放在同一包目录下

image-20220304201117948

4.6生命周期和作用域

image-20220304202038428

image-20220303163106933

4.7执行流程

image-20220307220911507

image-20220307220950251

image-20220307221001060

5.解决属性名和字段名不一致

  • 重新构建项目,只修改User中的属性
public class User {
    private int id;
    private String name;
    private String password;
}
  • 测试出现问题

image-20220305151048897

  • 原因

在数据库中查到的结果无法对应到User中去,导致虽然查到了pwd结果,但是无法填入

  • 解决1(起别名)
<!--    查询byId-->
    <select id="getUserById" resultType="User" parameterType="int">
        select id,name,pwd as password from mybatis.user where id = #{id}
    </select>
  • 解决2 (resultMap)
<!--    查询byId-->
    <resultMap id="UserMap" type="User">
<!--    column对应:数据库字段 property对应:type的字段-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserById" resultMap="UserMap" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>

image-20220305152801766

6.日志

6.1 日志工厂

image-20220305153843124

  • STDOUT_LOGGING
<!--    配置文件设置-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

image-20220305154457689

6.2 Log4J的介绍

  • 配置:
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=【%c】-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=【%p】【%d{yy-MM-dd}】【%c】%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  • 简单使用
@org.junit.Test
public void Test02(){
    Logger logger = Logger.getLogger(Test.class);
    logger.info("进入了test的log4j");
    logger.error("进入了error的log4j");
    logger.debug("进入了debug的log4j");
}

image-20220305160353148

  • 出现的问题 : 无法自动生成日志文件

    是因为log4j与slf4j冲突的解决。。不知道什么原因,我还有一个slf4j来和log4j竞争性的输出日志。。。并导致log4j无法正常的输出日志文件。。。我删除了项目结构中的库里面所有关于slf4j的jar包
    
    • 清除后的效果

image-20220305171026293

7.分页

7.1 使用limit

从第二个开始往下找两个

select * from user limit 1,2

image-20220305200801169

7.2 使用Mybatis

  • xml
<!--    分页查询-->
    <select id="Users" parameterType="map" resultType="User">
        select * from mybatis.user limit #{starIndex},#{pageSize}
    </select>
  • 测试
@org.junit.Test
public void Test03(){
    Map<String ,Integer> map  = new HashMap<>();
    map.put("starIndex",1);
    map.put("pageSize",2);
    List<User> users = mapper.Users(map);

    for (User user : users) {
        System.out.println(user);
    }
}

7.3 Mybatis的分页插件

image-20220305203030111

8.使用注解开发

8.1面向接口编程

image-20220305203339204

image-20220305203354078

8.2使用注解开发

image-20220305204903649

8.3使用注解完成CRUD

  • 编写接口增加注解

  • 注意 : 必须要在配置文件中注册对应的Mapper接口

image-20220306151214554

9.多对一处理

9.1环境的搭建

  • SQL创建表
CREATE TABLE `teacher` (
                           `id` INT(10) NOT NULL,
                           `name` VARCHAR(30) DEFAULT NULL,
                           PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');

CREATE TABLE `student` (
                       `id` INT(10) NOT NULL,
                       `name` VARCHAR(30) DEFAULT NULL,
                       `tid` INT(10) DEFAULT NULL,
                       PRIMARY KEY (`id`),
                       KEY `fktid` (`tid`),
                       CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
  • 项目搭建

image-20220306160443625

9.2 查询语句实现

按照查询嵌套处理

  • 思路:
1、先查出所有的学生
2、根据学生的tid查出老师

类似于子查询
  • 实现
<!--    查出所有学生,返回值是一个自定义的map-->
    <select id="FindAll" resultMap="SandT">
        select * from student
    </select>
    
<!--    定义这个map,类型其实还是student,association代表的是对象
        学生的tid属性对应的是老师这个属性,javaType说明teacher代表的java对象,然后绑定一个内查询getTeacher-->
    <resultMap id="SandT" type="Student">
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>

<!--    通过学生的id查询到老师,返回值是map中定义的Teacher对象-->
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>
  • 结果

image-20220306163240759

按照结果嵌套处理

<select id="FindAll2" resultMap="SandT2">
        select s.id sid,s.name sname,t.id tid,t.name tname
        from student s , teacher t
        where s.tid = t.id
    </select>

    <resultMap id="SandT2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"></result>
            <result property="id" column="tid"></result>
        </association>
    </resultMap>

10.一对多处理

按照结果嵌套处理

  • 实现
 <select id="getTeacher2" resultMap="TandS">
        select s.id sid , s.name sname , t.id tid , t.name tname
        from teacher t , student s
        where s.tid = t.id
    </select>

    <resultMap id="TandS" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
<!--     collection : 是集合   JavaType :指定的数据类型  ofType : 表示集合中的泛型-->
        <collection property="students" javaType="ArrayList" ofType="Student" >
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>
  • 结果

image-20220306225544545

按照查询嵌套处理

<select id="getTeacher3" resultMap="TaS">
    select * from teacher
</select>

<resultMap id="TaS" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Students" column="id" select="getStudents"/>
</resultMap>

<select id="getStudents" resultType="Student">
    select * from student where tid = #{id}
</select>

11.复杂查询的总结

image-20220306231826997

12.动态SQL

image-20220307135123767

12.1 环境搭建

  • 设置数据库
CREATE TABLE `blog`(
                       `id` VARCHAR(50) NOT NULL COMMENT '博客id',
                       `title` VARCHAR(100) NOT NULL COMMENT '博客标题',
                       `author` VARCHAR(30) NOT NULL COMMENT '博客作者',
                       `create_time` DATETIME NOT NULL COMMENT '创建时间',
                       `views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
  • 由于create_time无法匹配到java的属性,需要开启驼峰转换
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

12.2动态SQL之IF语句

  • xml语句
<!--    动态查询if-->
    <select id="queryIF" parameterType="map" resultType="blog">
        select * from blog where 1=1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>
  • 测试
@Test
    public void Test04(){

        Map<String,String> map = new HashMap<>();
        map.put("title","你好世界");
        List<Blog> blogs = mapper.queryIF(map);


        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

12.3动态SQL的常用标签

1.choose标签

image-20220307151507594

where标签 : 避免了在语句拼接是必须要先手写一个“where 1=1”的情况
choose标签 : 实现多个选择
when标签 : 选择的具体实现
otherwise标签 : 当所有选择的情况都不成立时,才成立
  • xml语句
<!--    查询queryChoose-->
    <select id="queryChoose" resultType="blog" parameterType="map">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <when test="views != null">
                    and views = #{views}
                </when>

                <otherwise>
                    1=1
                </otherwise>
            </choose>
        </where>
    </select>

2.set标签

set标签 :可以自动的删除多余的“,”,保证sql语句的正确性,可在update的定向修改上使用 
  • xml语句
<!--    使用set更新-->
    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author},
            </if>
        </set>
        where id = #{id}
    </update>
  • 测试
@Test
public void Test06(){
    try {
        Map<String,String> map = new HashMap<>();
        map.put("id","2");
        map.put("title","New你好世界");
        map.put("author","桂鹏程");
        int i = mapper.updateBlog(map);
        if (i>0){
            System.out.println("更新成功");
            sqlSession.commit();
        }
    } finally {
        sqlSession.close();
    }
}

12.4动态SQL之ForEach

  • SQL代码的引用

image-20220307200806791

  • xml代码
说明:
collection : 是要传入的集合名称,要与传入名对应
item : 是集合里面元素的类型名,与下面对应
open : 是拼接的开始
close : 是拼接的结束
separator : 是每一个item的分割
<!--    查询123-->
    <select id="query123" parameterType="map" resultType="blog">
        select * from blog where id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>
  • 测试
@Test
public void Test07(){
    Map<String,Object> map = new HashMap<>();
    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);ids.add(2);ids.add(3);
    map.put("ids",ids);
    List<Blog> blogs = mapper.query123(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
}
  • 结果

image-20220307202826339

13.缓存

13.1缓存简介

查询 : 连接数据库 , 耗资源
   一次查询的结果,给他寄存在一个可以直接取到的地方-->内存 : 缓存
   我们再一次查询到相同的数据时,直接走缓存,就不用走数据库了

image-20220307204014068

13.2Mybatis缓存

image-20220307205204211

13.3一级缓存

  • 测试
@Test
public void Test1(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User userById = mapper.getUserById(1);
    System.out.println(userById);
    System.out.println("===============================");
    User userById2 = mapper.getUserById(1);
    System.out.println(userById2);
    System.out.println("两次查询到的结果是否相等:"+((userById==userById2) ? "true":"false"));
}
  • 结果

image-20220307211224227

image-20220307211802299

  • 小结 : 一级缓存是默认开启的,只在一次sqlSession中有用,也就是拿到这个连接到关闭连接这个区间段,就是一个map

13.4二级缓存

  • 官方介绍
image-20220307212456822
  • 理解

image-20220307212545247

  • 步骤

1、 开启全局缓存

 <setting name="cacheEnabled" value="true"/>

2、 在Mapper.xml中使用二级缓存

复杂的,自定义的

<cache eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true">
</cache>

简单的

<cache></cache>
  • 测试

没开二级缓存

image-20220307213518600

开了二级缓存

image-20220307214506567

  • 问题

1、 我们要将实体类序列化,否则会报错

  • 小结

image-20220307214615748

13.5Mybatis缓存原理

image-20220307214953726

使用时,先看二级缓存,再看一级缓存

13.6自定义缓存Ehcache

  • 介绍

image-20220307215256444

  • 导包
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.0.0</version>
</dependency>