1
0

Mybatis.md 54 KB

[TOC]

Mybatis


环境:

  • JDK1.8
  • Mysql5.7
  • maven3.6.1
  • IDEA

1、简介


1.1、什么是mybatis

  • MyBatis 是一款优秀的持久层框架;
  • 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
  • 如何获得Mybatis

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

    1.2、持久化

    数据持久化

    • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
    • 内存:断电即失
    • 数据库(JDBC),io文件持久化
    • 生活方面的例子:冷藏,罐头

    为什么需要持久化

    • 不想丢掉一些对象
    • 内存太贵

    1.3、持久层

    Dao层,Service层,Controller层

    • 完成持久化工作的代码块
    • 层界限十分明显

    1.4、为什么需要Mybatis

    • 帮助程序员将数据存入到数据库中
    • 方便
    • 传统的JDBC代码太复杂,简化->框架->自动化
    • 不用Mybatis也可以。更容易上手。技术没有高低之分
    • 优点:
    • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件就可以了,易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
    • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
    • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
    • 提供xml标签,支持编写动态sql。
    • 最重要的一点,使用的人多!公司需要!

    2、第一个Mybatis程序


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

    2.1、搭建环境

    搭建数据库

    CREATE DATABASE `mybatis`;
    
    USE `mybatis`;
    
    DROP TABLE IF EXISTS `user`;
    
    CREATE TABLE `user` (
    `id` int(20) NOT NULL,
    `name` varchar(30) DEFAULT NULL,
    `pwd` varchar(30) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');
    

新建项目

  • 新建一个普通maven项目
  • 删除src目录
  • 导入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.6</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.2、创建一个模块

编写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.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://124.221.127.83:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/dao/UserMapper.xml"/>
    </mappers>
</configuration>

编写mybatis工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 使用mybatis工具类获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

}

2.3、编写代码

  • 实体类
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;
    }

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

  • Dao接口
public interface UseMapper {
    // 获取全部用户
    List<User> getUserList();

    // 根据ID查询用户
    User getUserById(int id);

    // 添加一个用户
    int addUser(User user);

    // 修改一个用户
    int updateUser(User user);

    // 根据id删除用户
    int deleteUser(int id);
}
  • 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">
<!--namespace=绑定一个对应的Dao/Mapper窗口-->
<mapper namespace="com.dao.UseMapper">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.entity.User">
        select *
        from user
    </select>

    <select id="getUserById" parameterType="int" resultType="com.entity.User">
        select * from user where id = #{id}
    </select>

    <!--对象中的属性可以直接提取出来-->
    <insert id="addUser" parameterType="com.entity.User">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>

    <update id="updateUser" parameterType="com.entity.User">
        update user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>

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

3、万能的Map


假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!

    // 万能的Map
    int addUser2(Map<String,Object> map);
    <insert id="addUser2" parameterType="map">
        insert into user (id,pwd) values (#{userid},#{password})
    </insert>

Map传递参数,直接在sql中取出key即可! 对象传递参数,直接在sql中取对象的属性即可! 只有一个基本类型参数的情况下,可以直接在sql中取到! 多个参数用Map,或者注解!

在sql语句中拼接通配符,会引起sql注入

    <select id="getUserLike" resultType="com.entity.User">
        select * from user where name like "%"#{value}"%"
    </select>

4、配置解析


4.1、核心配置文件

  • mybatis-config.xml
  • Mybatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。

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

4.2、环境变量

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

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

Mybatis 默认的事务管理器是JDBC,连接池:POOLED

4.3、属性

我们可以通过properties属性来引用配置文件

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

编写一个配置文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://124.221.127.83:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=root

在核心配置文件中引入

mybatis-config.xml (同时有的话,外面properties优先)

<?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>
    <!--引入外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </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/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4.4、类型别名 typeAliases

  • 类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置.
  • 意在降低冗余的全限定类名书写。
<!--可以给实体类起别名-->
<typeAliases>
    <typeAlias type="com.entity.User" alias="User"/>
</typeAliases>

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

在实体类比较少的时候,使用第一种方式。

如果实体类十分多,建议用第二种扫描包的方式。第一种可以DIY别名,第二种不行,如果非要改,需要在实体上增加注解。

@Alias("user")
public class User {
    ...
}

4.5、设置

设置名 描述 有效值 默认
cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true | false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 true | false false
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置

4.6、映射器

MapperRegistry:注册绑定我们的Mapper文件;

方式一: [推荐使用]

<mappers>
    <mapper resource="com/dao/UserMapper.xml"/>
</mappers>

方式二:

<mappers>
    <mapper class="com.dao.UserMapper"/>
</mappers>
  • 接口和它的Mapper必须同名
  • 接口和他的Mapper必须在同一包下

方式三:

<mappers>
    <package name="com.dao" />
</mappers>
  • 接口和它的Mapper必须同名
  • 接口和他的Mapper必须在同一包下

4.7、作用域和生命周期

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

image-20220228173708302

SqlSessionFactoryBuilder:

  • 一旦创建了SqlSessionFactory,就不再需要它了
  • 局部变量

SqlSessionFactory:

  • 就是数据库连接池。
  • 一旦被创建就应该在应用的运行期间一直存在 ,没有任何理由丢弃它或重新创建另一个实例 。 多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。
  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession

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

image-20220228174524811

这里面的每一个Mapper就代表每一个具体业务!

5、解决属性名和字段名不一致的问题


数据库中的字段

image-20220301123009394

新建一个项目,拷贝之前,测试实体字段不一致的情况 User

public class User {
    private int id;
    private String name;
    private String password;
}

image-20220301123406863

解决方法: 核心配置文件

  • 起别名
    <select id="getUserById" parameterType="int" resultType="com.entity.User">
        select id, name, pwd as password from user where id = #{id}
    </select>
  • resultMap 结果集映射
    <select id="getUserById" resultMap="UserMap" parameterType="int">
        select * from user where id = #{id}
    </select>

    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--column 数据库中的字段,property实体中的属性-->
        <result column="id" property="id"></result>
        <result column="name" property="name"></result>
        <result column="pwd" property="password"></result>
    </resultMap>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--column 数据库中的字段,property实体中的属性-->
        <result column="pwd" property="password"></result>
    </resultMap>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。
  • 如果这个世界总是这么简单就好了。

6、日志


6.1、日志工厂

如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手。 曾经:sout,debug 现在:日志工厂

image-20220301130041815

  • SLF4J
  • LOG4J [掌握]
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING [掌握]
  • NO_LOGGING

具体使用哪一个,在设置中设定 STDOUT_LOGGING 标志日志输出 mybatis-confi中

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

image-20220301130602068

6.2、Log4j

  1. 先导包
        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
  1. 新建log4j.properties文件
### set log levels ###
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/hou.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
  1. 配置实现
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>
  1. log4j的使用

image-20220301131606082

6.3、log4j简单使用

  1. 在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
  2. 日志对象,参数为当前类的class对象
 Logger logger = Logger.getLogger(UserDaoTest.class);
  1. 日志级别
logger.info("info: 测试log4j");
logger.debug("debug: 测试log4j");
logger.error("error:测试log4j");

7、分页


思考:为什么分页?

  • 减少数据的处理量

7.1、使用limit分页

SELECT * FROM user LIMIT startIndex,pageSize;
SELECT * FROM user LIMIT end; #[0, end]

使用MyBatis实现分页,核心SQL

  1. 接口
   // 分页
   List<User> getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml
   <!--分页查询-->
   <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
       select * from user limit #{startIndex},#{pageSize}
   </select>
  1. 测试
       @Test
       public void getUserByLimit(){
           SqlSession sqlSession = MybatisUtils.getSqlSession();
           UserMapper mapper = sqlSession.getMapper(UserMapper.class);
   
           Map<String, Integer> map = new HashMap<String, Integer>();
           map.put("startIndex", 1);
           map.put("pageSize", 2);
           List<User> userList = mapper.getUserByLimit(map);
   
           for(User user:userList){
               System.out.println(user);
           }
   
           sqlSession.close();
       }

7.2、使用RowBounds分页

不再使用SQL实现分页

  1. 接口
   //分页2
   List<User> getUserByRowBounds();
  1. mapper.xml
   <!--分页查询2-->
   <select id="getUserByRowBounds">
       select * from user limit #{startIndex},#{pageSize}
   </select>
  1. 测试
   @Test
   public void getUserByRow(){
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       // RowBounds实现
       RowBounds rowBounds = new RowBounds(1, 2);
   
       // 通过java代码层面
       List<User> userList = sqlSession.selectList
           ("com.dao.UserMapper.getUserByRowBounds",
            null,rowBounds);
   
       for (User user : userList) {
           System.out.println(user);
       }
   
       sqlSession.close();
   }

7.3、分页插件

image-20220301143250719

8、使用注解开发


8.1、面向接口编程

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现;
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构;

8.2、使用注解开发

  1. 删除 UserMapper.xml

  2. UserMapper

   public interface UserMapper {
   
       @Select("select * from user")
       List<User> getUsers();
   }
  1. 核心配置 mybatis-config.xml
    <!--绑定接口-->
   <mappers>
       <mapper class="com.hou.dao.UserMapper"></mapper>
   </mappers>
   

本质:反射机制

底层:动态代理

image-20220301151910709

Mybatis详细执行流程:

  1. Resource获取全局配置文件
  2. 实例化SqlsessionFactoryBuilder
  3. 解析配置文件流XMLCondigBuilder
  4. Configration所有的配置信息
  5. SqlSessionFactory实例化
  6. trasactional事务管理
  7. 创建executor执行器
  8. 创建SqlSession
  9. 实现CRUD
  10. 查看是否执行成功
  11. 提交事务
  12. 关闭

Mybatis详细执行流程

8.3、注解CRUD

编写接口

public interface UserMapper {
    // 获取全部用户
    @Select("select * from user")
    List<User> getUserList();

    // 方法存在多个参数,所有的参数必须加@Param
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

    @Insert("insert into user (id, name, pwd) values" +
            "(#{id},#{name},#{pwd})")
    int addUser(User user);

    @Update("update user set name=#{name}, pwd=#{pwd} " +
            "where id=#{id}")
    int updateUser(User user);

    @Delete("delete from user where id=#{id}")
    int deleteUser(@Param("id") int id);
}

MybatisUtile

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 使用mybatis工具类获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

}

Test 【注意:我们必须要将接口注册绑定到我们的核心配置文件中】

public class UserMapperTest {

    @Test
    public void getUserById(){
        // 获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getMapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            User user = userDao.getUserById(1);

            System.out.println(user);


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

    @Test
    public void addUser(){
        // 获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getMapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.addUser(new User(6, "kun","123"));

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

    @Test
    public void updateUser(){
        // 获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getMapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.updateUser(new User(6, "fang","123"));

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

    @Test
    public void deleteUser(){
        // 获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getMapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.deleteUser(6);

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

关于@Param( )注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名

#{} 和 ${}

  • 一般使用#号,防止注入
  • 两个都可以使用

9、Lombok


Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。

使用步骤:

  1. 在IDEA中安装Lombok插件,现在已经不需要安装,idea已经内置

  2. 在项目中导入Lombok的jar包

   <dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <version>1.18.8</version>
   </dependency>
  1. 在程序上加注解

在实体类上加注解

   @AllArgsConstructor // 有参构造
   @NoArgsConstructor // 无参构造
   @Data // 无参构造,get,set,toString,hashCode
   public class User {
       private int id;
       private String name;
       private String pwd;
   }

image-20220301155900195

10、多对一处理


image-20220301163509735

多对一:

  • 多个学生,对应一个老师
  • 对于学生而言,关联–多个学生,关联一个老师【多对一】
  • 对于老师而言,集合–一个老师,有很多个学生【一对多】

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');

测试环境搭建

  1. 导入lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件 【方式很多,随心选】
  6. 测试查询是否能够成功

10.1、按照查询嵌套处理

  1. 给StudentMapper接口增加方法
   // 获取所有学生及对应老师的信息
   public List<Student> getStudents();
  1. 编写对应打的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">
   <mapper namespace="com.kuang.dao.StudentMapper">
   
       <!--
       需求:获取所有学生及对应老师的信息
       思路:
           1. 获取所有学生的信息
           2. 根据获取的学生信息的老师ID->获取该老师的信息
           3. 思考问题,这样学生的结果集中应该包含老师,该如何处理呢,数据库中我们一般使用关联查询?
               1. 做一个结果集映射:StudentTeacher
               2. StudentTeacher结果集的类型为 Student
               3. 学生中老师的属性为teacher,对应数据库中为tid。
                  多个 [1,...)学生关联一个老师=> 一对一,一对多
               4. 查看官网找到:association – 一个复杂类型的关联;使用它来处理关联查询
       -->
       <select id="getStudents" resultMap="StudentTeacher">
       select * from student
      </select>
       <resultMap id="StudentTeacher" type="Student">
           <!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
           <association property="teacher"  column="tid" javaType="Teacher" select="getTeacher"/>
       </resultMap>
       <!--
       这里传递过来的id,只有一个属性的时候,下面可以写任何值
       association中column多参数配置:
           column="{key=value,key=value}"
           其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
       -->
       <select id="getTeacher" resultType="teacher">
         select * from teacher where id = #{id}
      </select>
   
   </mapper>
  1. 编写完毕去Mybatis配置文件中,注册Mapper!

  2. 注意点说明:

   <resultMap id="StudentTeacher" type="Student">
      <!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
      <association property="teacher"  column="{id=tid,name=tid}" javaType="Teacher" select="getTeacher"/>
   </resultMap>
   <!--
   这里传递过来的id,只有一个属性的时候,下面可以写任何值
   association中column多参数配置:
      column="{key=value,key=value}"
      其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
   -->
   <select id="getTeacher" resultType="teacher">
     select * from teacher where id = #{id} and name = #{name}
   </select>
  1. 测试
   @Test
   public void testGetStudents(){
      SqlSession session = MybatisUtils.getSession();
      StudentMapper mapper = session.getMapper(StudentMapper.class);
   
      List<Student> students = mapper.getStudents();
   
      for (Student student : students){
          System.out.println(
                  "学生名:"+ student.getName()
                          +"\t老师:"+student.getTeacher().getName());
     }
   }

10.2、按照结果嵌套查询

除了上面这种方式,还有其他思路吗?

我们还可以按照结果进行嵌套处理;

  1. 接口方法编写
   public List<Student> getStudents2();
  1. 编写对应的mapper文件
       <!--
       按查询结果嵌套处理
       思路:
       1. 直接查询出结果,进行结果集的映射
       -->
       <select id="getStudents2" resultMap="StudentTeacher2">
           select s.id sid, s.name sname, t.name tname, t.id tid
           from student s,
                teacher t
           where s.tid = t.id
       </select>
   
       <resultMap id="StudentTeacher2" type="Student">
           <!--
           id是作为唯一标识的,当和其他对象实例对比的时候,
           这个id很有用,尤其是应用到缓存和内嵌的结果映射。
           result可以有多个,分别对应数据库中的各个字段和实体类中的属性。
           -->
           <id property="id" column="sid"/>
           <result property="name" column="sname"/>
           <!--关联对象property 关联对象在Student实体类中的属性-->
           <association property="teacher" javaType="Teacher">
               <id property="id" column="tid"/>
               <result property="name" column="tname"/>
           </association>
       </resultMap>
  1. 去mybatis-config文件中注入【此处应该处理过了】
       <!--绑定接口-->
       <mappers>
           <mapper resource="com/dao/TeacherMapper.xml"/>
           <mapper resource="com/dao/StudentMapper.xml"/>
       </mappers>
  1. 测试
       @Test
       public void testGetStudents2() {
           SqlSession sqlSession = MybatisUtils.getSqlSession();
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
   
           List<Student> students = mapper.getStudents2();
   
           for (Student student : students) {
               System.out.println(student);
           }
           sqlSession.close();
       }

小结

  • 按照查询进行嵌套处理就像SQL中的子查询
  • 按照结果进行嵌套处理就像SQL中的联表查询

回顾Mysql多对一查询方式:

  • 子查询
  • 联表查询

11、一对多处理


比如:一个老师拥有多个学生! 对于老师而言,就是一对多的关系!

11.1、环境搭建

  1. 环境搭建,和刚才一样 实体类:
   @Data
   public class Student {
       private int id;
       private String name;
       private int tid;
   
   }
   @Data
   public class Teacher {
       private int id;
       private String name;
   
       // 一个老师拥有多个学生
       private List<Student> students;
   }

..... 和之前一样,搭建测试的环境!

11.2、按照结果嵌套查询

  1. TeacherMapper接口编写方法
   // 获取指定老师,及老师下的所有学生
   Teacher getTeacher(@Param("tid") int id);
  1. 编写接口对应的Mapper配置文件
       <!--
       思路:
       1. 从学生表和老师表中查出学生id,学生姓名,老师姓名
       2. 对查询出来的操作做结果集映射
           1. 集合的话,使用collection!
               JavaType和ofType都是用来指定对象类型的
               JavaType是用来指定entity中属性的类型
               ofType-相当于泛型-指定的是映射到list集合属性中entity的类型。
       -->
       <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">
           <id property="id" column="tid"/>
           <result property="name" column="tname"/>
           <collection property="students" ofType="Student">
               <result property="id" column="sid" />
               <result property="name" column="sname" />
               <result property="tid" column="tid" />
           </collection>
       </resultMap>
  1. 将Mapper文件注册到MyBatis-config文件中
       <!--绑定接口-->
       <mappers>
           <mapper resource="com/dao/TeacherMapper.xml"/>
           <mapper resource="com/dao/StudentMapper.xml"/>
       </mappers>
  1. 测试
       @Test
       public void test() {
           SqlSession sqlSession = MybatisUtils.getSqlSession();
           TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
           Teacher teacher = mapper.getTeacher(1);
           List<Student> students = teacher.getStudents();
           for (Student student : students) {
               System.out.println(student);
           }
           sqlSession.close();
       }

11.3、按照查询嵌套处理

  1. TeacherMapper接口编写方法
   public Teacher getTeacher2(int id);
  1. 编写接口对应的Mapper配置文件
       <select id="getTeacher2" resultMap="TeacherStudent2">
           select * from teacher where id = #{tid}
       </select>
       <resultMap id="TeacherStudent2" type="Teacher">
           <id property="id" column="id"/>
           <result property="name" column="name"/>
           <!--column是一对多的外键 , 写的是一的主键的列名-->
           <collection property="students" ofType="Student" column="id" select="getStudentByTeacherId"/>
       </resultMap>
       <select id="getStudentByTeacherId" resultType="Student">
           select * from student where tid = #{id}
       </select>
  1. 将Mapper文件注册到MyBatis-config文件中

  2. 测试

       @Test
       public void test() {
           SqlSession sqlSession = MybatisUtils.getSqlSession();
           TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
           Teacher teacher = mapper.getTeacher2(1);
           System.out.println(teacher);
           sqlSession.close();
       }

小结

  1. 关联-association
  2. 集合-collection
  3. 所以association是用于一对一和多对一,而collection是用于一对多的关系
  4. javaType和ofType都是用来指定对象类型的
    • JavaType是用来指定entity中属性的类型
    • ofType指定的是映射到list集合属性中entity的类型,泛型的约束类型

注意说明:

  1. 保证SQL的可读性,尽量通俗易懂
  2. 根据实际要求,尽量编写性能更高的SQL语句
  3. 注意属性名和字段不一致的问题
  4. 注意一对多和多对一 中:字段和属性对应的问题
  5. 尽量使用Log4j,通过日志来查看自己的错误

面试高频:

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

12、动态SQL


什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.

官网描述:
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

  -------------------------------
  - if
  - choose (when, otherwise)
  - trim (where, set)
  - foreach
  -------------------------------

我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。

那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。

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
  1. 创建mybatis基础工程
  2. IDUtils工具类
  3. 实体类编写
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
  1. mapper接口和xml文件
public interface BlogMapper {
    // 插入数据
    int addBlog(Blog blog);
}

    <insert id="addBlog" parameterType="Blog">
        insert into blog (id, title, author, create_time, views)
        values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
  1. mybatis核心配置文件,下环线自动转换
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.entity.Blog" alias="Blog"/>
    </typeAliases>

  1. 插入数据
    @Test
    public void addInitBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setId(IDUtils.genId());
        blog.setTitle("Mybatis如此简单");
        blog.setAuthor("狂神说");
        blog.setCreateTime(new Date());
        blog.setViews(9999);

        mapper.addBlog(blog);

        blog.setId(IDUtils.genId());
        blog.setTitle("Java如此简单");
        mapper.addBlog(blog);

        blog.setId(IDUtils.genId());
        blog.setTitle("Spring如此简单");
        mapper.addBlog(blog);

        blog.setId(IDUtils.genId());
        blog.setTitle("微服务如此简单");
        mapper.addBlog(blog);

        sqlSession.close();
    }

12.2、关键字

if

需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

  1. 编写接口类
   // 需求1
   List<Blog> queryBlogIf(Map map);
  1. 编写SQL语句
   <!--需求1:
   根据作者名字和博客名字来查询博客!
   如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
   -->
   <select id="queryBlogIf" 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>
  1. 测试
   @Test
   public void testQueryBlogIf(){
      SqlSession session = MybatisUtils.getSession();
      BlogMapper mapper = session.getMapper(BlogMapper.class);
   
      HashMap<String, String> map = new HashMap<String, String>();
      map.put("title","Mybatis如此简单");
      map.put("author","狂神说");
      List<Blog> blogs = mapper.queryBlogIf(map);
   
      System.out.println(blogs);
   
      session.close();
   }

where

修改上面的SQL语句;

<select id="queryBlogIf" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <if test="title != null">
          title = #{title}
       </if>
       <if test="author != null">
          and author = #{author}
       </if>
   </where>
</select>

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

choose

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

<select id="queryBlogChoose" parameterType="map" resultType="blog">
  select * from blog
   <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>

MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

set

同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

<!--注意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>

trim

    <insert id="addBlog" parameterType="Blog">
        insert into blog
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="title != null">
                title,
            </if>
            <if test="author != null">
                author,
            </if>
            <if test="createTime != null">
                create_time,
            </if>
            <if test="views != 0">
                views
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null">
            #{id},
        </if>
        <if test="title != null">
            #{title},
        </if>
        <if test="author != null">
            #{author},
        </if>
        <if test="createTime != null">
            #{createTime},
        </if>
        <if test="views != 0">
            #{views}
        </if>
        </trim>;
    </insert>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

SQL片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

提取SQL片段:

<sql id="if-title-author">
   <if test="title != null">
      title = #{title}
   </if>
   <if test="author != null">
      and author = #{author}
   </if>
</sql>

引用SQL片段:

<select id="queryBlogIf" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
       <include refid="if-title-author"></include>
       <!-- 在这里还可以引用其他的 sql 片段 -->
   </where>
</select>

注意:

  1. 最好基于 单表来定义 sql 片段,提高片段的可重用性
  2. 在 sql 片段中不要包括 where

ForEach

  • 动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。
  • foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
  • 提示你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

将数据库中前三个数据的id修改为1,2,3;

需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

  1. 编写接口
   List<Blog> queryBlogForeach(Map map);
  1. 编写SQL语句
   <select id="queryBlogForeach" parameterType="map" resultType="blog">
     select * from blog
      <where>
          <!--
          collection:指定输入对象中的集合属性
          item:每次遍历生成的对象
          open:开始遍历时的拼接字符串
          close:结束时拼接的字符串
          separator:遍历对象之间需要拼接的字符串
   	   index:迭代次数,从0k
          select * from blog where 1=1 and (id=1 or id=2 or id=3)
        -->
          <foreach collection="ids"  item="id" open="(" close=")" separator="or">
             id=#{id}
          </foreach>
      </where>
   </select>
  1. 测试
   @Test
   public void testQueryBlogForeach(){
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
       HashMap map = new HashMap();
       List<Integer> ids = new ArrayList<Integer>();
       ids.add(1);
       ids.add(2);
       ids.add(3);
       map.put("ids",ids);
       List<Blog> blogs = mapper.queryBlogForeach(map);
       for (Blog blog : blogs) {
           System.out.println(blog);
       }
   
       sqlSession.close();
   }

小结

其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧。

13、缓存


13.1、简介

  1. 什么是缓存
  2. 存在内存中的临时数据。
  3. 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库查询文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

  4. 为什么使用缓存

  • 减少和数据库的交互次数,减少系统开销,提高系统效率。
  1. 什么样的数据能使用缓存
  • 经常查询并且不经常改变的数据。【可以使用缓存】

13.2、Mybatis缓存

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

13.3、一级缓存

一级缓存也叫本地缓存:

与数据库同一次会话期间查询到的数据会放在本地缓存中。

以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

测试

  1. 在mybatis中加入日志,方便测试结果
  2. 编写接口方法
// 根据id查询用户
User queryUserById(@Param("id") int id);
  1. 接口对应的Mapper文件
<select id="queryUserById" resultType="user">
  select * from user where id = #{id}
</select>
  1. 测试
@Test
public void testQueryUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    User user = mapper.queryUserById(1);
    System.out.println(user);
    User user2 = mapper.queryUserById(1);
    System.out.println(user2);
    System.out.println(user==user2);

    sqlSession.close();
}
  1. 结果分析

image-20220313144802945

一级缓存失效的四种情况

一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它; 一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

  1. sqlSession不同

结论:每个sqlSession中的缓存相互独立

  1. sqlSession相同,查询条件不同

观察结果:发现发送了两条SQL语句!很正常的理解

结论:当前缓存中,不存在这个数据

  1. sqlSession相同,两次查询之间执行了增删改操作!

观察结果:查询在中间执行了增删改操作后,重新执行了

结论:因为增删改操作可能会对当前数据产生影响

  1. sqlSession相同,手动清除一级缓存

结论:清理缓存相当于刷新内存

小结:一级缓存默认是开启的,只有一次SqlSession中有效,也就是拿到连接到关闭连接的区间段-----相当于一个map

13.4、二级缓存

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

使用步骤

  1. 开启全局缓存 【mybatis-config.xml】
<!--虽然默认已经开启了,但是还是需要显示的声明,以便其他开发者知道-->
<setting name="cacheEnabled" value="true"/>
  1. 去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】
<cache/>

官方示例=====>查看官方文档
<cache
 eviction="FIFO"
 flushInterval="60000"
 size="512"
 readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
  1. 代码测试

所有的实体类先实现序列化接口

测试代码

@Test
public void test(){
    SqlSession sqlSession1 = MybatisUtils.getSqlSession();
    SqlSession sqlSession2 = MybatisUtils.getSqlSession();

    UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
    UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);

    User user1 = mapper1.queryUserById(1);
    System.out.println(user1);
    sqlSession1.close();

    User user2 = mapper2.queryUserById(1);
    System.out.println(user2);
    System.out.println(user1==user2);

    sqlSession2.close();
}

结论

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
  • 查出的数据都会被默认先放在一级缓存中
  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

13.5、缓存原理

缓存原理