MyBatis详解

1.简介

1. Mybatis是什么?
  • MyBatis 是一款优秀的持久层框架;
  • 支持定制化 SQL、存储过程以及高级映射;
  • 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集;
  • 使用简单的 XML 或注解来配置和映射原生信息.

那我们该如何获得Mybatis?

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

  • GitHub: https://github.com/mybatis/mybatis-3

  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.2 持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化
  • 内存:断电即失
  • 数据库(jdbc),io文件持久化
1.3持久层

Dao层(接口)、Service层(业务)、Controller层(控制)…

  • 完成持久化工作的代码块
  • 层界限十分明显,分工明确
1.4为什么需要Mybatis?
  • 帮助我们将数据存入到数据库中,与数据库进行交互
  • mybatis可以自己写sql,因此灵活性更高,也更方便
  • 传统的jdbc代码太复杂。简化、框架、自动化

Mybatis特点

  • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
  • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
  • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的orm字段关系映射。
  • 提供对象关系映射标签,支持对象关系组建维护。
  • 提供xml标签,支持编写动态sql

2.我的第一个Mybatis程序

步骤:搭建环境—>导入Mybatis—>编写程序—>测试🆗

2.1搭建环境

搭建数据库:(博主这里选择的可视化软件是navicat)

新建项目

  1. 新建maven普通项目

  2. 删除src

  3. 导入maven依赖

    <!--  导入依赖  -->
    <dependencies>
    <!--  mysql驱动   -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
    
    <!--    mybatis    -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
    
        <!--    junit    -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    
2.2建立一个module
  • 编写mybatis核心配置文件

    <?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"/>
                    <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="zc123"/>
                </dataSource>
            </environment>
        </environments>
    
    </configuration>
    
  • 编写mybatis工具类

    //SqlSessionFactory---->SqlSession
    public class MybatisUtils {
    
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            try {
                //使用mybatis第一步:获取SqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        public static SqlSession getSqlSession(){
            //等同于下方return sqlSessionFactory.openSession();
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }
    }
    
2.3编写代码
  • 编写实体类

    package com.orange.pojo;
    
    //实体类
    
    public class User {
        private int id;
        private String name;
        private  String pwd;
    
        //无参
        public User() {
        }
    
        //有参
        public User(int id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        //set、get方法
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        //toString
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
    
  • 编写Dao接口

    public interface UserDao {
        List<User> getUserList();
    }
    
  • 编写接口实现类

    接口实现类由原来的UserDaoImpl转换为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">
    
    <!--namespace=绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.orange.dao.UserDao">
    
        <!--  select查询语句  -->
        <select id="getUserList" resultType="com.orange.pojo.User">
        select * from mybatis.user
        </select>
    </mapper>
    
2.4测试

导入junit相关文件,编写测试类进行测试

    <!--    junit    -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

3.CRUD

3.1 namespace
namespace中的包名必须和接口中的包名一致
3.2 select(查询)

选择、 查询语句

  • id:就是对应的namespace中的方法名
  • resultType:SQL语句执行的返回值
  • parameterType:返回值类型
  1. 编写接口

    //根据id查询用户
    User getUserByID(int id);
    
  2. 编写对应的mapper中的sql语句

    <select id="getUserByID" parameterType="int" resultType="com.orange.pojo.User">
    select * from mybatis.user where id= #{id}
    </select>
    
  3. 测试

    @Test
    public void getUserByID(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.getUserByID(2);  //查询2号用户
        System.out.println(user);
    
        sqlSession.close();
    }
    
3.3 insert(插入)
  1. 编写接口

      //insert 插入一个用户
     int addUser(User user); //下一步去补充标签
    
  2. 编写对应的mapper中的sql语句

     <insert id="addUser" parameterType="com.orange.pojo.User">
            insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd});
        </insert>
    
  3. 测试

     @Test
        //增删改需要提交事务
        public void addUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            UserDao mapper = sqlSession.getMapper(UserDao.class);
    
            int res = mapper.addUser(new User(5,"学友","444322")); //插入4号用户
            if(res>0){
                System.out.println("插入成功");
            }
            //提交事务
            sqlSession.commit();
            sqlSession.close();
    
        }
    
    
3.4 Update(修改)
  1. 编写接口

      //修改用户
        int updateUser(User user);
    
  2. 编写对应的mapper中的sql语句

     <update id="updateUser" parameterType="com.orange.pojo.User">
            update mybatis.user set name=#{name},pwd=#{pwd}  where id=#{id};
        </update>
    
  3. 测试

     @Test
        public void updateUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            UserDao mapper = sqlSession.getMapper(UserDao.class);
    
            mapper.updateUser(new User(1,"冰冰","1114444"));
    
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    
3.5 Delete(删除)
  1. 编写接口

        //删除用户
        int deleteUser(int user);
    
  2. 编写对应的mapper中的sql语句

      <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id = #{id}
        </delete>
    
  3. 测试

        @Test
        public void deleteUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            UserDao mapper = sqlSession.getMapper(UserDao.class);
    
            mapper.deleteUser(2);
    
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    

注意:增删改操作需要提交事务

Map

假设我们的实体类,数据库中的表,字段,参数等过多,可以考虑使用map

  1. 编写接口

     int addUser2(Map<String,Object> map); 
    
  2. 编写对应的mapper中的sql语句

    <!--传递map中的key-->
    <insert id="addUser" parameterType="map">
            insert into mybatis.user(name,pwd) values (#{name},#{pwd});
     </insert>
    
  3. 测试

     @Test
        //增删改需要提交事务
        public void addUser2(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            UserDao mapper = sqlSession.getMapper(UserDao.class);
    
            Map<String,Object> map = new HashMap<String,Object>();
            
            map.put("userid", 5);
            map.put("password" ,"4444555");
            
            mapper.addUser2(map);
            sqlSession.close();
    
        }
    
    

map传递参数,直接在sql中取出key即可;parameterType="map"

对象传递参数,直接在sql中取对象的属性即可;parameterType="Object"

只有一个基本类型参数的情况下,可以直接在sql中获取到。


4.配置解析

4.1核心配置文件

MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

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

MyBatis 可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

mybatis默认的事务管理器就是 JDBC,连接池 POOLED

4.3属性(properties)

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。(db.properties)

编写配置文件:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=zc123
4.4类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

<!--给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.orange.pojo.User" alias="User"/>
    </typeAliases>
4.5生命周期和作用域(Scope)

作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。

SqlSessionFactoryBuilder

  • 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。
  • SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。

SqlSessionFactory

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • 说白了就是数据库连接池
  • SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession

  • 连接到连接池的一个请求
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完之后赶紧关闭,否则资源被占用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WwUAW0yP-1651294917995)(../../typora-user-images/image-20220419150459694.png)]

这里面的每一个mapper,就代表一个业务.


5.日志

5.1日志工厂

数据库操作出现异常的时候,需要排错,那么日志就是最好的助手 ~

以前:sout、debug

现在:Mybatis 通过使用内置的日志工厂提供日志功能。

logImpl 可选的值有:

  • SLF4J
  • Log4j 2
  • Log4j (掌握)
  • JDK logging
  • COMMONS_LOGGING
  • STDOUT_LOGGING(掌握)
  • NO_LOGGING(没有日志输出)
<configuration>
  <settings>
 
    <setting name="logImpl" value="LOG4J"/>

  </settings>
</configuration>

STDOUT_LOGGING标准日志输出

在核心配置文件中配置日志

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0GyfUxsn-1651294917997)(../../typora-user-images/image-20220420104408841.png)]

5.2 Log4j

什么是Log4j

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件;
  • 也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程;
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
  1. 导入Log4j的包

     <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
      </dependency>
    
  2. 在CLASSPATH下建立log4j.properties

    #将等级为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
    
  3. 配置Log4j实现

    <settings>
       <setting name="logImpl" value="LOG4J"/>
    </settings>
    
  4. 测试运行

简单使用:

  • 在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;

  • 日志对象,参数为当前类的对象

    static Logger logger = Logger.getLogger(UserDaoTest.class);

  • 日志级别

    Logger.info("info:进入了testLog4j");
    Logger.debug("debug:进入了testLog4j");
    Logger.error("error:进入了testLog4j");
    

复制项目模块:

  • 新建module–>maven
  • resources下导入mybatis-config.xml,db.propertis
  • 建包com.orange.xx
  • 建utils导入工具类MybatisUtils
  • 建pojo导入实体类User
  • 建dao导入接口跟实现的sql:UserMapper、UserMapper.xml
  • test建包导入测试类
  • pom.xml里在build中配置resources,来防止我们资源导出失败的问题

6.Lombok

使用步骤:

  • 在IDEA中安装Lombok插件

  • 在IDEA中导入Lombok的架包

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.4</version>
    </dependency>
    
  • 在实体类上加注解即可

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    

注解:

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data         
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows

说明:

@Data:  //用的最多,生成无参构造,get,set,tostring,hashcode,equals

@AllArgsConstructor  //有参构造
@NoArgsConstructor  //无参构造

7.多对一处理

举个在课堂上一位老师在跟多位学生讲课的栗子😜

  • 多个学生,对应一个老师
  • 对于学生而言,关联 多个学生关联一个老师【多对一】
  • 对于老师而言, 集合 一个老师有很多学生【一对多】
测试环境搭建
  1. 导入lombok
  2. 新建实体类Teacher、Student
  3. 建立mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或文件
  6. 测试查询
按照查询嵌套处理
<!--  select s.id, s.name, t.name   from student s,teacher t where s.tid=t.id;  -->
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
<!--   对象:association  集合: collection    -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>

    </resultMap>
    
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>

8.一对多处理

例如:一个老师拥有多个学生

环境搭建

实体类:

@Data
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}
@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
按照查询嵌套处理
<!--  按结果嵌套查询  -->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname, t.id tid
        from student s,teacher t
        where s.tid =t.id and t.id = #{tid}
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--   对象:association  集合: collection    -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>

    </resultMap>
小结
  • 关联–association–【多对一】
  • 集合-- collection–【一对多】
  • javaType & ofType
    • JavaType: 用来指定实体类中属性的类型
    • ofType:用来指定映射到List或者集合中的pojo类型

9.动态SQL

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach
搭建环境
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

创建一个基础工程:

  • 导包

  • 编写配置文件

  • 编写实体类

    @Data
    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date  creatTime;
        private int views;
    }
    
  • 编写实体类对应的Mapper接口和Mapper.xml文件

if
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog where 1=1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and title = #{author}
    </if>
</select>
choose (when, otherwise)
<select id="queryBlogchoose" parameterType="map" resultType="blog">
    select * from mybatis.blog where
      <where>
          <choose>
              <when test="title != null">
              title = #{title}
              </when>
              <when test="author != null">
                 and author = #{author}
              </when>
              <otherwise>
                  and views = #{views}
              </otherwise>
          </choose>
      </where>
</select>
trim (where, set)
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>
SQL片段
  1. 使用SQL标签抽取公共的部分

    <sql id="if-title-aurhor">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>
    
  2. 在需要使用的地方用include 标签引用即可

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
         <include refid="if-title-aurhor"></include>
        </where>
    </select>
    
foreach
<!--  select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)  -->
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="and  (" close=")" separator="or">
                     id=#{id}
           </foreach>
        </where>
    </select>

10.缓存

10.1 MyBatis缓存
  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存,默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存),
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口定义二级缓存。
10.2 一级缓存
  • 一级缓存也叫本地缓存: SqlSession

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中。如果以后需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库。

一级缓存测试:

  • 编写Mapper接口方法:

     //根据id查询用户
     User queryUserById(@Param("id") int id);
    
  • 编写接口对应的Mapper.xml文件:

     <select id="queryUserById" resultType="user">
         select * from user where id = #{id}
     </select>
    
  • 编写测试程序:

      @Test
        public void queryUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            //查一次
            User user1 = mapper.queryUserById(1);
            System.out.println(user1);
    
            System.out.println("================================");
            User user2 = mapper.queryUserById(1);//再查一次
            System.out.println(user2);
    
            System.out.println(user1==user2);
            
            sqlSession.close();
        }
    

一级缓存失效的情况

  • 每个SqlSession中的缓存相互独立,SqlSession不同,没有使用到当前的一级缓存。

  • SqlSession相同,查询条件不同,当前缓存中,不存在这个数据。

  • SqlSession相同,两次查询之间执行了增删改操作,增删改操作可能会对当前数据产生影响。

  • SqlSession相同,手动清除一级缓存:session.clearCache();//手动清除缓存

10.3二级缓存
  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 它是基于namespace级别的缓存,一个名称空间对应一个二级缓存。
  • 二级缓存工作机制为:
    • 一个会话查询的一条数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是二级缓存开启后,一级缓存中的数据被保存到二级缓存中,新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

开启二级缓存:

  • 修改mybatis-config.xml文件:

     <setting name="cacheEnabled" value="true"/>
    
  • 在每个mapper.xml中配置使用二级缓存:

     <cache/>
     <cache
       <!--配置创建了一个 FIFO 缓存-->
       eviction="FIFO" 
       <!--每隔 60 秒刷新-->
       flush Interval="60000" 
       <!--最多可以存储结果对象或列表的512个引用-->
       size="512"
       read Only="true"/>
    
  • 代码测试

     @Test
     public void testQueryUserById(){
         SqlSession session = MybatisUtils.getSession();
         SqlSession session2 = MybatisUtils.getSession();
         Mapper mapper = session.getMapper(Mapper.class);
         Mapper mapper2 = session2.getMapper(Mapper.class);
         User user = mapper.queryUserById(1);
         System.out.println(user);
         session.close();
         User user2 = mapper2.queryUserById(1);
         System.out.println(user2);
         System.out.println(user==user2);
         session2.close();
     }
    
10.4自定义缓存
  • 自定义缓存对象,该对象必须实现 org.apache.ibatis.cache.Cache 接口。

  • 为了方便日后的开发工作和降低学习成本,我们可以使用第三方缓存,推荐使用 EhCache。

  • EhCache 是一个快速的、轻量级的、易于使用的、进程内的缓存。它支持 read-only 和 read/write 缓存,内存和磁盘缓存。是一个非常轻量级的缓存实现,而且从 1.2 之后就支持了集群,目前的最新版本是 2.8。


😄这是博主在学习MyBatis过程中作的笔记总结,道阻且长,希望能给到C友帮助~最后在这里祝大家五一节快乐!💐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

果力成°

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值