第一章:了解Mybatis Plus(摘自官网)

1.1 Mybatis Plus介绍

  • Mybatis Plus(简称MP)是一个Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,为简化开发、提高效率而生。
  • 官网

愿景: 我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

Mybatis Plus介绍.png

1.2 代码以及文档

1.3 特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

1.4 架构

MybatisPlus的架构.png

第二章:整合Mybatis Plus

2.1 准备工作

  • MySQL 5.7版本以上。
  • JDK 11。
  • IDEA 2021+。
  • Sql脚本:
  1. -- 创建数据库
  2. CREATE DATABASE IF NOT EXISTS mp
  3. DEFAULT CHARACTER SET utf8mb4
  4. DEFAULT COLLATE utf8mb4_general_ci;
  1. -- 创建测试表
  2. CREATE TABLE `tb_user` (
  3. `id` BIGINT ( 20 ) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  4. `user_name` VARCHAR ( 20 ) NOT NULL COMMENT '用户名',
  5. `password` VARCHAR ( 20 ) NOT NULL COMMENT '密码',
  6. `name` VARCHAR ( 30 ) DEFAULT NULL COMMENT '姓名',
  7. `age` INT ( 11 ) DEFAULT NULL COMMENT '年龄',
  8. `email` VARCHAR ( 50 ) DEFAULT NULL COMMENT '邮箱',
  9. PRIMARY KEY ( `id` )
  10. ) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4;
  1. -- 插入测试数据
  2. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('1', 'zhangsan', '123456', '张三', '18', 'test1@qq.com');
  3. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('2', 'lisi', '123456', '李四', '20', 'test2@qq.com');
  4. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('3', 'wangwu', '123456', '王五', '28', 'test3@qq.com');
  5. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('4', 'zhaoliu', '123456', '赵六', '21', 'test4@qq.com');
  6. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('5', 'sunqi', '123456', '孙七', '24', 'test5@qq.com');

2.2 SpringBoot整合Mybatis Plus

2.2.1 导入相关依赖

  • pom.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.1</version>
  9. <relativePath/>
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>mp</artifactId>
  13. <version>0.0.1</version>
  14. <name>mp</name>
  15. <properties>
  16. <java.version>11</java.version>
  17. </properties>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-web</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>mysql</groupId>
  25. <artifactId>mysql-connector-java</artifactId>
  26. <scope>runtime</scope>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.projectlombok</groupId>
  30. <artifactId>lombok</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <dependency>
  39. <groupId>com.baomidou</groupId>
  40. <artifactId>mybatis-plus-boot-starter</artifactId>
  41. <version>3.4.3.1</version>
  42. </dependency>
  43. </dependencies>
  44. <build>
  45. <plugins>
  46. <plugin>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-maven-plugin</artifactId>
  49. <configuration>
  50. <excludes>
  51. <exclude>
  52. <groupId>org.projectlombok</groupId>
  53. <artifactId>lombok</artifactId>
  54. </exclude>
  55. </excludes>
  56. </configuration>
  57. </plugin>
  58. </plugins>
  59. </build>
  60. </project>

2.2.2 编写application.yml

  • application.yml
  1. # 服务器配置
  2. server:
  3. # 端口
  4. port: 8080
  5. servlet:
  6. # 项目名称
  7. context-path: /mp
  8. # tomcat的配置
  9. tomcat:
  10. # tomcat的URI编码
  11. uri-encoding: UTF-8
  12. # tomcat最大线程数,默认为200
  13. max-threads: 800
  14. # Tomcat启动初始化的线程数,默认值25
  15. min-spare-threads: 30
  16. max-http-header-size: 65536
  17. spring:
  18. # 配置数据源
  19. datasource:
  20. driver-class-name: com.mysql.cj.jdbc.Driver
  21. url: jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
  22. username: root
  23. password: 123456
  24. # Hikari 连接池配置
  25. hikari:
  26. # 最小空闲连接数量
  27. minimum-idle: 5
  28. # 空闲连接存活最大时间,默认600000(10分钟)
  29. idle-timeout: 180000
  30. # 连接池最大连接数,默认是10
  31. maximum-pool-size: 1000
  32. # 此属性控制从池返回的连接的默认自动提交行为,默认值:true
  33. auto-commit: true
  34. # 连接池名称
  35. pool-name: MPHikariCP
  36. # 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
  37. max-lifetime: 1800000
  38. # 数据库连接超时时间,默认30秒,即30000
  39. connection-timeout: 30000
  40. connection-test-query: SELECT 1
  41. data-source-properties:
  42. useInformationSchema: true
  43. # 开启日志
  44. mybatis-plus:
  45. configuration:
  46. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2.2.3 编写POJO

  • User.java
  1. package com.example.mp.domain;
  2. import com.baomidou.mybatisplus.annotation.TableField;
  3. import com.baomidou.mybatisplus.annotation.TableName;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import java.io.Serializable;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-06-17 21:01
  12. */
  13. @Data
  14. @NoArgsConstructor
  15. @AllArgsConstructor
  16. @TableName("tb_user")
  17. public class User implements Serializable {
  18. /**
  19. * 主键
  20. */
  21. private Long id;
  22. /**
  23. * 用户名
  24. */
  25. @TableField("user_name")
  26. private String username;
  27. /**
  28. * 密码
  29. */
  30. private String password;
  31. /**
  32. * 姓名
  33. */
  34. private String name;
  35. /**
  36. * 年龄
  37. */
  38. private Integer age;
  39. /**
  40. * 电子邮件
  41. */
  42. private String email;
  43. }

2.2.4 编写Mapper

  • UserMapper.java
  1. package com.example.mp.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.example.mp.domain.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2021-06-17 21:10
  9. */
  10. @Mapper
  11. public interface UserMapper extends BaseMapper<User> {
  12. }

2.2.5 编写启动类

  • MpApplication.java
  1. package com.example.mp;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan("com.example.mp.mapper") //设置mapper接口的扫描包
  7. public class MpApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(MpApplication.class, args);
  10. }
  11. }

2.2.6 编写测试用例

  • MpApplicationTests.java
  1. package com.example.mp;
  2. import com.example.mp.domain.User;
  3. import com.example.mp.mapper.UserMapper;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import java.util.List;
  8. @SpringBootTest
  9. class MpApplicationTests {
  10. @Autowired
  11. private UserMapper userMapper;
  12. @Test
  13. public void testSelect() {
  14. List<User> userList = userMapper.selectList(null);
  15. userList.forEach(System.out::println);
  16. }
  17. }

第三章:通用CRUD

3.1 概述

  • 通过上面的学习,我们知道通过继承BaseMapper可以实现各种各样的单表操作,下面将详细讲解这些操作。

BaseMapper的方法.png

3.2 插入操作

3.2.1 方法定义

  • 方法:
  1. /**
  2. * 插入一条记录
  3. *
  4. * @param entity 实体对象
  5. */
  6. int insert(T entity);

3.2.2 测试用例

  • 示例:
  1. package com.example.mp;
  2. import com.example.mp.domain.User;
  3. import com.example.mp.mapper.UserMapper;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. @SpringBootTest
  8. class MpApplicationTests {
  9. @Autowired
  10. private UserMapper userMapper;
  11. @Test
  12. public void testInsert(){
  13. User user = new User();
  14. user.setUsername("zhangsan");
  15. user.setPassword("123456");
  16. user.setName("张三");
  17. user.setAge(18);
  18. user.setEmail("123456@qq.com");
  19. int count = userMapper.insert(user);
  20. System.out.println("count = " + count); //数据库受影响的行数
  21. System.out.println("user.getId() = " + user.getId()); //自增后的id会回填到对象中
  22. }
  23. }

3.2.3 测试

  • 结果:

插入操作测试.png

  • 数据库记录:

插入操作中数据库查询记录.png

  • 可以看到,数据已经写入到数据库中了,但是,id的值是不正确的,我们期望的是数据库自增长,实际是MP生成了id的值写入到数据库中。
  • MP支持的id策略:
  1. package com.baomidou.mybatisplus.annotation;
  2. import lombok.Getter;
  3. /**
  4. * 生成ID类型枚举类
  5. *
  6. * @author hubin
  7. * @since 2015-11-10
  8. */
  9. @Getter
  10. public enum IdType {
  11. /**
  12. * 数据库ID自增
  13. * <p>该类型请确保数据库设置了 ID自增 否则无效</p>
  14. */
  15. AUTO(0),
  16. /**
  17. * 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
  18. */
  19. NONE(1),
  20. /**
  21. * 用户输入ID
  22. * <p>该类型可以通过自己注册自动填充插件进行填充</p>
  23. */
  24. INPUT(2),
  25. /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
  26. /**
  27. * 分配ID (主键类型为number或string),
  28. * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法)
  29. *
  30. * @since 3.3.0
  31. */
  32. ASSIGN_ID(3),
  33. /**
  34. * 分配UUID (主键类型为 string)
  35. * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-",""))
  36. */
  37. ASSIGN_UUID(4);
  38. private final int key;
  39. IdType(int key) {
  40. this.key = key;
  41. }
  42. }
  • 修改User对象:
  1. package com.example.mp.domain;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.AllArgsConstructor;
  7. import lombok.Data;
  8. import lombok.NoArgsConstructor;
  9. import java.io.Serializable;
  10. /**
  11. * @author 许大仙
  12. * @version 1.0
  13. * @since 2021-06-17 21:01
  14. */
  15. @Data
  16. @NoArgsConstructor
  17. @AllArgsConstructor
  18. @TableName("tb_user")
  19. public class User implements Serializable {
  20. /**
  21. * 主键
  22. */
  23. @TableId(type= IdType.AUTO)
  24. private Long id;
  25. /**
  26. * 用户名
  27. */
  28. @TableField("user_name")
  29. private String username;
  30. /**
  31. * 密码
  32. */
  33. private String password;
  34. /**
  35. * 姓名
  36. */
  37. private String name;
  38. /**
  39. * 年龄
  40. */
  41. private Integer age;
  42. /**
  43. * 电子邮件
  44. */
  45. private String email;
  46. }
  • 数据插入成功:

插入操作中数据插入成功.png

3.2.4 @TableField注解

  • 在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有2个:
    • ①对象中的属性名和字段名不一致的问题(非驼峰)。
    • ②对象中的属性字段在表中不存在的问题。
  • 示例:
  1. package com.example.mp.domain;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.AllArgsConstructor;
  7. import lombok.Data;
  8. import lombok.NoArgsConstructor;
  9. import java.io.Serializable;
  10. /**
  11. * @author 许大仙
  12. * @version 1.0
  13. * @since 2021-06-17 21:01
  14. */
  15. @Data
  16. @NoArgsConstructor
  17. @AllArgsConstructor
  18. @TableName("tb_user")
  19. public class User implements Serializable {
  20. @TableId(type= IdType.AUTO)
  21. private Long id;
  22. @TableField("user_name") //解决字段名不一致
  23. private String username;
  24. @TableField(select = false) //该字段不加入到查询中
  25. private String password;
  26. private String name;
  27. private Integer age;
  28. private String email;
  29. @TableField(exist = false)
  30. private String address; //该字段在数据库表中不存在
  31. }

3.3 更新操作

3.3.1 概述

  • 在MP中,更新操作有2种,一种是根据id更新,另一种是根据条件更新。

3.3.2 根据id更新

  • 方法定义:
  1. /**
  2. * 根据 ID 修改
  3. *
  4. * @param entity 实体对象(对象属性可以为null)
  5. */
  6. int updateById(@Param(Constants.ENTITY) T entity);
  • 测试:
  1. package com.example.mp;
  2. import com.example.mp.domain.User;
  3. import com.example.mp.mapper.UserMapper;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-06-18 19:22
  11. */
  12. @SpringBootTest
  13. public class TestUpdate {
  14. @Autowired
  15. private UserMapper userMapper;
  16. @Test
  17. public void testUpdateById() {
  18. User user = new User();
  19. user.setId(1L);
  20. user.setUsername("许大仙");
  21. //根据id更新,更新不为null的字段,返回更新的条数
  22. int result = userMapper.updateById(user);
  23. System.out.println("result = " + result);
  24. }
  25. }
  • 结果:

根据id更新.png

  • 数据库记录:

根据id更新的数据库记录.png

3.3.3 根据条件更新

  • 方法定义:
  1. /**
  2. * 根据 whereEntity 条件,更新记录
  3. *
  4. * @param entity 实体对象 (set 条件值,可以为 null)
  5. * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
  6. */
  7. int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
  • 测试:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.Wrapper;
  3. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  4. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  5. import com.example.mp.domain.User;
  6. import com.example.mp.mapper.UserMapper;
  7. import org.junit.jupiter.api.Test;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.boot.test.context.SpringBootTest;
  10. /**
  11. * @author 许大仙
  12. * @version 1.0
  13. * @since 2021-06-18 19:22
  14. */
  15. @SpringBootTest
  16. public class TestUpdate {
  17. @Autowired
  18. private UserMapper userMapper;
  19. @Test
  20. public void testUpdate() {
  21. //封装更新字段的对象
  22. User user = new User();
  23. user.setAge(18);
  24. //封装更新条件的对象
  25. QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  26. queryWrapper.eq("user_name", "zhangsan");
  27. int result = userMapper.update(user, queryWrapper);
  28. System.out.println("result = " + result);
  29. }
  30. @Test
  31. public void testUpdate2() {
  32. UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
  33. updateWrapper.set("age", 18)
  34. .set("password", "123456").eq("user_name", "zhangsan");
  35. int result = userMapper.update(null, updateWrapper);
  36. System.out.println("result = " + result);
  37. }
  38. }
  • 结果:

根据条件更新的结果.png

  • 数据库记录:

根据条件更新的数据库记录.png

3.4 删除操作

3.4.1 deleteById

  • 方法定义:
  1. /**
  2. * 根据 ID 删除
  3. *
  4. * @param id 主键ID
  5. */
  6. int deleteById(Serializable id);
  • 测试:
  1. package com.example.mp;
  2. import com.example.mp.mapper.UserMapper;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2021-06-18 20:04
  10. */
  11. @SpringBootTest
  12. public class TestDeleteById {
  13. @Autowired
  14. private UserMapper userMapper;
  15. @Test
  16. public void test(){
  17. //执行删除操作
  18. int result = userMapper.deleteById(6);
  19. System.out.println("result = " + result);
  20. }
  21. }
  • 结果:

deleteById的结果.png

3.4.2 deleteByMap

  • 方法定义:
  1. /**
  2. * 根据 columnMap 条件,删除记录
  3. *
  4. * @param columnMap 表字段 map 对象
  5. */
  6. int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
  • 测试:
  1. package com.example.mp;
  2. import com.example.mp.mapper.UserMapper;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-06-18 20:10
  12. */
  13. @SpringBootTest
  14. public class TestDeleteByMap {
  15. @Autowired
  16. private UserMapper userMapper;
  17. @Test
  18. public void test(){
  19. Map<String,Object> map = new HashMap<>();
  20. map.put("id", "5");
  21. map.put("age", "24");
  22. //将map中的元素设置为删除的条件,多个条件之间是and的关系
  23. int result = userMapper.deleteByMap(map);
  24. System.out.println("result = " + result);
  25. }
  26. }
  • 结果:

deleteByMap的结果.png

3.4.3 delete

  • 方法定义:
  1. /**
  2. * 根据 entity 条件,删除记录
  3. *
  4. * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
  5. */
  6. int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 测试:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-06-18 20:31
  12. */
  13. @SpringBootTest
  14. public class TestDelete {
  15. @Autowired
  16. private UserMapper userMapper;
  17. @Test
  18. public void test() {
  19. QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  20. queryWrapper.gt("age", 20);
  21. userMapper.delete(queryWrapper);
  22. }
  23. }
  • 结果:

delete的结果.png

3.4.4 deleteBatchIds

  • 方法定义:
  1. /**
  2. * 删除(根据ID 批量删除)
  3. *
  4. * @param idList 主键ID列表(不能为 null 以及 empty)
  5. */
  6. int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
  • 测试:
  1. package com.example.mp;
  2. import com.example.mp.mapper.UserMapper;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import java.util.List;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-06-18 20:39
  11. */
  12. @SpringBootTest
  13. public class TestDeleteBatchIds {
  14. @Autowired
  15. private UserMapper userMapper;
  16. @Test
  17. public void test() {
  18. //根据id集合批量删除
  19. int result = userMapper.deleteBatchIds(List.of(1, 2, 3));
  20. System.out.println("result = " + result);
  21. }
  22. }
  • 结果:

deleteBatchIds的结果.png

3.5 查询操作

3.5.1 概述

  • MP提供了多种查询操作,包括根据id查询、批量查询、查询单条数据、查询列表、分页查询等操作。

3.5.2 selectById

  • 方法定义:
  1. /**
  2. * 根据 ID 查询
  3. *
  4. * @param id 主键ID
  5. */
  6. T selectById(Serializable id);
  • 示例:
  1. package com.example.mp;
  2. import com.example.mp.domain.User;
  3. import com.example.mp.mapper.UserMapper;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-06-18 21:00
  11. */
  12. @SpringBootTest
  13. public class TestSelectById {
  14. @Autowired
  15. private UserMapper userMapper;
  16. @Test
  17. public void test(){
  18. //根据id查询数据
  19. User user = userMapper.selectById(1);
  20. System.out.println("user = " + user);
  21. }
  22. }
  • 结果:

selectById的结果.png

3.5.3 selectBatchIds

  • 方法定义:
  1. /**
  2. * 查询(根据ID 批量查询)
  3. *
  4. * @param idList 主键ID列表(不能为 null 以及 empty)
  5. */
  6. List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
  • 测试:
  1. package com.example.mp;
  2. import com.example.mp.domain.User;
  3. import com.example.mp.mapper.UserMapper;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import java.util.List;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-06-18 22:01
  12. */
  13. @SpringBootTest
  14. public class TestSelectBatchIds {
  15. @Autowired
  16. private UserMapper userMapper;
  17. @Test
  18. public void test() {
  19. //根据id集合批量查询
  20. List<User> userList = userMapper.selectBatchIds(List.of(1, 2, 3));
  21. System.out.println("userList = " + userList);
  22. }
  23. }
  • 结果:

selectBatchIds的结果.png

3.5.4 selectOne

  • 方法定义:
  1. /**
  2. * 根据 entity 条件,查询一条记录
  3. *
  4. * @param queryWrapper 实体对象封装操作类(可以为 null)
  5. */
  6. T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 测试:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-06-18 22:08
  12. */
  13. @SpringBootTest
  14. public class TestSelectOne {
  15. @Autowired
  16. private UserMapper userMapper;
  17. @Test
  18. public void test() {
  19. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  20. lambdaQueryWrapper.eq(User::getUsername, "zhangsan");
  21. //根据条件查询一条数据,如果结果超过一条则报错
  22. User user = userMapper.selectOne(lambdaQueryWrapper);
  23. System.out.println("user = " + user);
  24. }
  25. }
  • 结果:

selectOne的结果.png

3.5.5 selectList

  • 方法定义:
  1. /**
  2. * 根据 entity 条件,查询全部记录
  3. *
  4. * @param queryWrapper 实体对象封装操作类(可以为 null)
  5. */
  6. List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 测试:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.List;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-06-18 22:14
  13. */
  14. @SpringBootTest
  15. public class TestSelectList {
  16. @Autowired
  17. private UserMapper userMapper;
  18. @Test
  19. public void test() {
  20. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  21. lambdaQueryWrapper.ge(User::getId, 3);
  22. //根据条件查询数据
  23. List<User> userList = userMapper.selectList(lambdaQueryWrapper);
  24. System.out.println("userList = " + userList);
  25. }
  26. }
  • 结果:

selectList的结果.png

3.5.6 selectCount

  • 方法定义:
  1. /**
  2. * 根据 Wrapper 条件,查询总记录数
  3. *
  4. * @param queryWrapper 实体对象封装操作类(可以为 null)
  5. */
  6. Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 测试:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-06-18 22:21
  12. */
  13. @SpringBootTest
  14. public class TestSelectCount {
  15. @Autowired
  16. private UserMapper userMapper;
  17. @Test
  18. public void test() {
  19. //根据条件查询数据条数
  20. Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>().ge(User::getId, 2));
  21. System.out.println("count = " + count);
  22. }
  23. }
  • 结果:

selectCount的结果.png

3.5.7 selectPage

  • 方法定义:
  1. /**
  2. * 根据 entity 条件,查询全部记录(并翻页)
  3. *
  4. * @param page 分页查询条件(可以为 RowBounds.DEFAULT)
  5. * @param queryWrapper 实体对象封装操作类(可以为 null)
  6. */
  7. <P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 配置分页插件:
  1. package com.example.mp.config;
  2. import com.baomidou.mybatisplus.annotation.DbType;
  3. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  4. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-06-18 22:42
  11. */
  12. @Configuration
  13. public class MybatisPlusConfig {
  14. // 配置分页插件
  15. @Bean
  16. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  17. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  18. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  19. return interceptor;
  20. }
  21. }
  • 测试:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  4. import com.example.mp.domain.User;
  5. import com.example.mp.mapper.UserMapper;
  6. import org.junit.jupiter.api.Test;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import java.util.List;
  10. /**
  11. * @author 许大仙
  12. * @version 1.0
  13. * @since 2021-06-18 22:36
  14. */
  15. @SpringBootTest
  16. public class TestSelectPage {
  17. @Autowired
  18. private UserMapper userMapper;
  19. @Test
  20. public void test(){
  21. Page<User> page = new Page<>(1,5);
  22. Page<User> selectPage = userMapper.selectPage(page, new QueryWrapper<>());
  23. long total = selectPage.getTotal();
  24. long pages = selectPage.getPages();
  25. System.out.println("数据总条数 = " + total);
  26. System.out.println("总页数 = " + pages);
  27. List<User> userList = selectPage.getRecords();
  28. System.out.println("userList = " + userList);
  29. }
  30. }
  • 结果:

selectPage的结果.png

3.6 SQL注入原理

  • 我们知道,MP在启动后会将BaseMapper中的一系列的方法注册到MappedStatement中,那么是如何注入的?流程是什么?
  • 在MP中,ISqlInjector负责SQL的注入工作,它是一个接口,AbstractSqlInjector是它的实现类,实现关系如下:

ISqlInjector的实现关系.png

  • AbstractSqlInjector中,主要是由inspectInject方法进行注入的,源码如下:
  1. package com.baomidou.mybatisplus.core.injector;
  2. import com.baomidou.mybatisplus.core.mapper.Mapper;
  3. import com.baomidou.mybatisplus.core.metadata.TableInfo;
  4. import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
  5. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  6. import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
  7. import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
  8. import org.apache.ibatis.builder.MapperBuilderAssistant;
  9. import org.apache.ibatis.logging.Log;
  10. import org.apache.ibatis.logging.LogFactory;
  11. import java.util.List;
  12. import java.util.Set;
  13. /**
  14. * SQL 自动注入器
  15. *
  16. * @author hubin
  17. * @since 2018-04-07
  18. */
  19. public abstract class AbstractSqlInjector implements ISqlInjector {
  20. private static final Log logger = LogFactory.getLog(AbstractSqlInjector.class);
  21. @Override
  22. public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
  23. Class<?> modelClass = ReflectionKit.getSuperClassGenericType(mapperClass, Mapper.class, 0);
  24. if (modelClass != null) {
  25. String className = mapperClass.toString();
  26. Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
  27. if (!mapperRegistryCache.contains(className)) {
  28. List<AbstractMethod> methodList = this.getMethodList(mapperClass);
  29. if (CollectionUtils.isNotEmpty(methodList)) {
  30. TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
  31. // 循环注入自定义方法
  32. methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
  33. } else {
  34. logger.debug(mapperClass.toString() + ", No effective injection method was found.");
  35. }
  36. mapperRegistryCache.add(className);
  37. }
  38. }
  39. }
  40. /**
  41. * <p>
  42. * 获取 注入的方法
  43. * </p>
  44. *
  45. * @param mapperClass 当前mapper
  46. * @return 注入的方法集合
  47. * @since 3.1.2 add mapperClass
  48. */
  49. public abstract List<AbstractMethod> getMethodList(Class<?> mapperClass);
  50. }
  • 在实现方法中,methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));是关键,循环遍历方法,进行注入。
  • 查看m.inject方法,可以看到如下的代码:
  1. public abstract class AbstractMethod implements Constants {
  2. protected static final Log logger = LogFactory.getLog(AbstractMethod.class);
  3. protected Configuration configuration;
  4. protected LanguageDriver languageDriver;
  5. protected MapperBuilderAssistant builderAssistant;
  6. /**
  7. * 注入自定义方法
  8. */
  9. public void inject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
  10. this.configuration = builderAssistant.getConfiguration();
  11. this.builderAssistant = builderAssistant;
  12. this.languageDriver = configuration.getDefaultScriptingLanguageInstance();
  13. /* 注入自定义方法 */
  14. injectMappedStatement(mapperClass, modelClass, tableInfo);
  15. }
  16. ....
  17. }
  • 由此可知,最终是通过调用injectMappedStatement进行真正的注入的。
  1. /**
  2. * 注入自定义 MappedStatement
  3. *
  4. * @param mapperClass mapper 接口
  5. * @param modelClass mapper 泛型
  6. * @param tableInfo 数据库表反射信息
  7. * @return MappedStatement
  8. */
  9. public abstract MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo);
  • injectMappedStatement方法的实现如下:

injectMappedStatement方法的实现.png

  • SelectById为例查看:
  1. public class SelectById extends AbstractMethod {
  2. @Override
  3. public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
  4. SqlMethod sqlMethod = SqlMethod.SELECT_BY_ID;
  5. SqlSource sqlSource = new RawSqlSource(configuration, String.format(sqlMethod.getSql(),
  6. sqlSelectColumns(tableInfo, false),
  7. tableInfo.getTableName(), tableInfo.getKeyColumn(), tableInfo.getKeyProperty(),
  8. tableInfo.getLogicDeleteSql(true, true)), Object.class);
  9. return this.addSelectMappedStatementForTable(mapperClass, getMethod(sqlMethod), sqlSource, tableInfo);
  10. }
  11. }
  • 可以看到,生成了SqlSource对象,再将SQL通过addSelectMappedStatementForTable方法添加到了MappedStatement中。

第四章:Mybatis Plus的配置

4.1 概述

  • 在MP中有大量的配置,其中有一部分是Mybatis原生的配置,另一部分是MP的配置。

4.2 基本配置

4.2.1 configLocation

  • MyBatis配置文件位置,如果有单独的MyBatis配置,将其路径配置到 configLocation 中。
  • SpringBoot:
  1. mybatis-plus:
  2. config-location: classpath:mybatis-config.xml

4.2.2 mapperLocations

  • Mybatis Mapper所对应的XML文件配置,如果在Mapper中有自定义方法(XML中有自定义实现),需要进行该配置,告诉Mapper所对应的XML文件位置。
  • SpringBoot:
  1. mybatis-plus:
  2. mapper-locations: classpath*:mybatis/*.xml

4.2.3 typeAliasesPackage

  • Mybatis别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在Mapper对应的XML文件中可以直接使用类名,而不用使用全限定的类名(即XML中调用的时候不用包含包名)。
  • SpringBoot:
  1. mybatis-plus:
  2. type-aliases-package: com.example.mp.domain

4.3 进阶配置

4.3.1 mapUnderscoreToCamelCase

  • mapUnderscoreToCamelCase
    • 类型:boolean。
    • 默认值:true。
  • 是否开启自动驼峰命名规则的映射,即从经典数据库列名A_COLUMN(下划线命名)到经典的Java属性名AColumn的类似映射。

    注意:

    • 此属性在Mybatis中的原默认值为false,在MybatisPlux中,此属性也将用于生成最终的SQL的select body。
    • 如果数据库命名符合规则则无需使用@TableField注解指定数据库字段名。
  • SpringBoot:

  1. mybatis-plus:
  2. configuration:
  3. #关闭自动驼峰映射,该参数不能和mybatis-plus.config-location同时存在,默认值为true,一般情况下,默认即可
  4. map-underscore-to-camel-case: false

4.3.2 cacheEnabled

  • cacheEnabled:
    • 类型:boolean。
    • 默认值:true。
  • 全局的开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为true。
  • SpringBoot:
  1. mybatis-plus:
  2. configuration:
  3. # 全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true,一般情况下,默认即可
  4. cacheEnabled: false

4.4 DB策略配置

4.4.1 idType

  • idType:
    • 类型:com.baomidou.mybatisplus.annotation.IdType。
    • 默认值:ASSIGN_ID。
  • 全局设置主键类型,设置后,即可省略实体对象中的@TableId(type=IdType.AUTO)配置。
  • SpringBoot:
  1. mybatis-plus:
  2. global-config:
  3. db-config:
  4. id-type: auto

4.4.2 tablePrefix

  • tablePrefix:
    • 类型:String。
    • 默认值:null。
  • 表名前缀,全局配置后可省略@TableName()的配置。
  • SpringBoot:
  1. mybatis-plus:
  2. global-config:
  3. db-config:
  4. table-prefix: tb_

第五章:条件构造器

5.1 概述

  • 在MP中,Wrapper接口的实现类关系如下:

Wrapper接口的实现类关系.png

  • 可以看到,AbstractWrapperAbstractChainWrapper是重点实现,我们重点学习AbstractWrapper及其实现子类。

说明:QueryWrapper(LambdaQueryWrapper)和UpdateWrapper(LambdaUpdateWrapper)的父类用于生成sql的where条件, entity属性也用于生成sql的where条件。 注意:entity生成的where条件与使用各个api生成的where条件没有任何关联行为

5.2 allEq

5.2.1 说明

  1. allEq(Map<R, V> params)
  1. allEq(Map<R, V> params, boolean null2IsNull)
  1. allEq(boolean condition, Map<R, V> params, boolean null2IsNull)

参数说明:

  • params:key是数据库字段名,value为字段值。
  • null2IsNull:为true则在map的value为null时调用isNull方法,为false时则忽略value为null。

5.2.2 应用示例

  • 示例:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. * @author 许大仙
  13. * @version 1.0
  14. * @since 2021-06-19 11:04
  15. */
  16. @SpringBootTest
  17. public class TestAllEq {
  18. @Autowired
  19. private UserMapper userMapper;
  20. @Test
  21. public void testAllEq() {
  22. QueryWrapper<User> wrapper = new QueryWrapper<>();
  23. //设置条件
  24. Map<String,Object> params = new HashMap<>();
  25. params.put("name","zhangsan");
  26. params.put("age", null);
  27. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (name = ? AND age IS NULL)
  28. wrapper.allEq(params);
  29. List<User> userList = userMapper.selectList(wrapper);
  30. System.out.println("userList = " + userList);
  31. }
  32. @Test
  33. public void testAllEqNull2IsNullFalse() {
  34. QueryWrapper<User> wrapper = new QueryWrapper<>();
  35. //设置条件
  36. Map<String,Object> params = new HashMap<>();
  37. params.put("name","zhangsan");
  38. params.put("age", null);
  39. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (name = ?)
  40. wrapper.allEq(params,false);
  41. List<User> userList = userMapper.selectList(wrapper);
  42. System.out.println("userList = " + userList);
  43. }
  44. }

5.3 基本操作比较

  • eq:等于=
  • ne:不等于<>
  • gt:大于>
  • lt:小于<
  • ge:大于等于>=
  • le:小于等于le
  • between:between 值1 AND 值2
  • notBetween:NOT between 值1 AND 值2
  • in:字段 IN (值1,值2,...)
  • notIn:字段 NOT IN (值1,值2,...)
  • 示例:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.List;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-06-19 11:20
  13. */
  14. @SpringBootTest
  15. public class TestEq {
  16. @Autowired
  17. private UserMapper userMapper;
  18. @Test
  19. public void test() {
  20. QueryWrapper<User> wrapper = new QueryWrapper<>();
  21. wrapper.eq("password", "123456")
  22. .ge("age", 20)
  23. .in("name", "张三", "李四", "王五");
  24. List<User> userList = userMapper.selectList(wrapper);
  25. System.out.println("userList = " + userList);
  26. }
  27. }

5.4 模糊查询

  • like:
    • LIKE ‘%值%’。
    • 例: like("name", "王")—->name like '%王%'
  • notlike:
    • NOT LIKE ‘%值%’。
    • 例: notLike("name", "王")—->name not like '%王%'
  • likeLeft:
    • LIKE ‘%值’。
    • 例: likeLeft("name", "王")—->name like '%王'
  • LikeRight:
    • LIKE ‘值%’。
    • 例: likeRight("name", "王")—->name like '王%'
  • 示例:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.List;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-06-19 11:27
  13. */
  14. @SpringBootTest
  15. public class TestLike {
  16. @Autowired
  17. private UserMapper userMapper;
  18. @Test
  19. public void test() {
  20. QueryWrapper<User> wrapper = new QueryWrapper<>();
  21. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (name LIKE %张%)
  22. wrapper.like("name", "张");
  23. List<User> userList = userMapper.selectList(wrapper);
  24. System.out.println("userList = " + userList);
  25. }
  26. }

5.5 排序

  • orderBy:
    • 排序:ORDER BY 字段, …
    • 例: orderBy(true, true, "id", "name")—->order by id ASC,name ASC
  • orderByAsc:
    • 排序:ORDER BY 字段, … ASC。
    • 例: orderByAsc("id", "name")—->order by id ASC,name ASC
  • orderByDesc:
    • 排序:ORDER BY 字段, … DESC。
    • 例: orderByDesc("id", "name")—->order by id DESC,name DESC
  • 示例:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.List;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-06-19 13:40
  13. */
  14. @SpringBootTest
  15. public class TestOrderBy {
  16. @Autowired
  17. private UserMapper userMapper;
  18. @Test
  19. public void test() {
  20. QueryWrapper<User> wrapper = new QueryWrapper<>();
  21. //SELECT id,user_name,password,name,age,email FROM tb_user ORDER BY age ASC
  22. wrapper.orderByAsc("age");
  23. List<User> userList = userMapper.selectList(wrapper);
  24. System.out.println("userList = " + userList);
  25. }
  26. }

5.6 逻辑查询

  • or:
    • 拼接 OR。
    • 例: eq("id",1).or().eq("name","老王")—->id = 1 or name = '老王'
  • and:
    • AND 嵌套。
    • 例: and(i -> i.eq("name", "李白").ne("status", "活着"))—->and (name = '李白' and status <> '活着')
  • 示例:
  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.List;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-06-19 13:44
  13. */
  14. @SpringBootTest
  15. public class TestOrAnd {
  16. @Autowired
  17. private UserMapper userMapper;
  18. @Test
  19. public void test(){
  20. QueryWrapper<User> wrapper = new QueryWrapper<>();
  21. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE (name = ? OR age = ?)
  22. wrapper.eq("name", "张三").or().eq("age", 18);
  23. List<User> userList = this.userMapper.selectList(wrapper);
  24. System.out.println("userList = " + userList);
  25. }
  26. }

5.7 select

  • select:设置查询字段。

  • 示例:

  1. package com.example.mp;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.example.mp.domain.User;
  4. import com.example.mp.mapper.UserMapper;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.List;
  9. /**
  10. * @author 许大仙
  11. * @version 1.0
  12. * @since 2021-06-19 13:48
  13. */
  14. @SpringBootTest
  15. public class TestSelect {
  16. @Autowired
  17. private UserMapper userMapper;
  18. @Test
  19. public void test() {
  20. QueryWrapper<User> wrapper = new QueryWrapper<>();
  21. //SELECT user_name,age,password FROM tb_user WHERE (name = ? OR age = ?)
  22. wrapper
  23. .eq("name", "张三")
  24. .or()
  25. .eq("age", 18)
  26. .select("user_name", "age", "password");
  27. List<User> userList = this.userMapper.selectList(wrapper);
  28. System.out.println("userList = " + userList);
  29. }
  30. }