Mybatis-plus


typora-root-url: img

Mybatis-Plus

一、Mybatis-Plus介绍

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发 提
高效率而生。该框架由baomidou(苞米豆)组织开发并且开源的。

官网:https://mybatis.plus/ 或 https://mp.baomidou.com/ github地址:
https://github.com/baomidou/mybatis-plus 码云地址:https://gitee.com/baomidou/mybatis-plus

1.2、支持的数据库

MyBatisPlus支持如下数据库:

  • mysql mariadb oracle db2 h2 hsql sqlite postgresql sqlserver
  • 达梦数据库 虚谷数据库 人大金仓数据库

1.3 特性

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

1.4 架构

在这里插入图片描述

Mybatis主要包含以下模块:

核心功能(core),基于Mybatis的封装,提供了Mybatis Plus的基础配置类与核心功能,如内置通用 Mapper,
Lambda 表达式查询等。

注解(annotation),提供了Mybatis Plus中注解的定义。
扩展功能(extension),提供扩展及插件功能,包括分页插件 通用 Service扩展 性能分析插件等。
代码生成器(generator):通过代码生成器可以快速生成 Mapper接口 Entity实体类 Mapper XML Service
Controller 等各个模块的代码,极大的提升了开发效率。
执行流程:
(1)扫描注解Entity,反射提取注解信息如:表名称 字段名称等信息。
(2)分析注解信息并基于com.baomidou.mybatisplus.core.enums的SQL模板生成基本CRUD SQL。
(3)最后将这些SQL注入到Mybatis环境中。
因此Mybatis plus无需编写CRUD SQL语句,只需继承BaseMapper,魔术般的拥有了CRUD功能(通用CRUD)。

二、快速入门

2.1 准备环境

  • JDK 8+
  • Maven 3.3.9
  • IDEA 2018.2
  • MySQL5.7

2.2 创建数据库以及表

创建数据库并设置字符集为utf-8:

CREATE DATABASE `mybatis_plus_demo` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

创建表和测试数据:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for system_user
-- ----------------------------
DROP TABLE IF EXISTS `system_user`;
CREATE TABLE `system_user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
  `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `age` int(11) NULL DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
  `birthday` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of system_user
-- ----------------------------
INSERT INTO `system_user` VALUES (1, 'zhangsan', '123456', '张三', 18, '1234@qq.com', '2023-06-16 23:14:36');
INSERT INTO `system_user` VALUES (2, 'lisi', '123456', '李四', 19, '1235@qq.com', '2023-06-17 23:15:03');
INSERT INTO `system_user` VALUES (3, 'wangwu', '123456', '王五', 20, '1236@qq.com', '2023-06-16 23:15:28');
INSERT INTO `system_user` VALUES (4, 'zhaoliu', '123456', '赵六', 21, '1237@qq.com', '2023-06-16 23:15:45');
INSERT INTO `system_user` VALUES (5, 'sunqi', '123456', '孙七', 22, '1238@qq.com', '2023-06-16 23:16:04');

SET FOREIGN_KEY_CHECKS = 1;

2.3 搭建工程

2.3.1创建项目

创建maven工程,分别填写GroupId ArtifactId和Version,如下:

<groupId>com.xidida.mp</groupId>
<artifactId>xidida-mybatis-plus</artifactId>
<version>1.0-SNAPSHOT</version>

2.3.2 导入依赖

导入maven依赖,由于本例采用Spring boot技术,使用mybatis-plus-boot-starter能与其便捷集成:
版本规划:
Spring boot: 2.1.3.RELEASE
mybatis-plus: 3.1.0

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xidida.mp</groupId>
    <artifactId>xidida-mybatis-plus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--    springboot的依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--        测试      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--简化代码的工具包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mybatis-plus的springboot支持-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
    </dependencies>

</project>

2.3.3编写application.properties

# 启动端口
server.port=8081
# 项目名
spring.application.name = xidida-mybatis-plus
# 数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库链接
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_plus_demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
# 数据库账号
spring.datasource.username=root
# 数据库密码
spring.datasource.password=123456
# Logger Config
logging.level.root=debug

2.3.4编写pojo

package com.xidida.mp.pojo;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:30
 * @notes
 */
@TableName("system_user")// 指定对应的类名
@Data//可以描述:getter、setter等等方法
public class SystemUser {

    @TableId("id")// 指定主键字段名
    private Long id;
    @TableField("user_name")// 指定所对应的字段名  字段名是不区分大小写的
    private String userName;
    @TableField("PASSWORD")
    private String password;
    @TableField("NAME")
    private String name;
    @TableField("AGE")
    private Integer age;
    @TableField("EMAIL")
    private String email;
    @TableField("BIRTHDAY")// 指定时间类型对应的方法
    private LocalDateTime birthday;
}

@Data:lombok的注解,使用它可以省略getter/setter方法。
@NoArgsConstructor: 生成无参构造 方法
@AllArgsConstructor:生成所有参数构造 方法,参数顺序与属性定义顺序一致。
@TableName:指定表名
@TableId:指定主键名

注意:使用lombok需要安装插件

在这里插入图片描述

2.3.5编写mapper

package com.xidida.mp.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xidida.mp.pojo.SystemUser;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:38
 * @notes
 */
// 需要 继承 mybatis 的BaseMapper这里使用了泛型来指定 pojo类
public interface SystemUserMapper extends BaseMapper<SystemUser> {

}

2.3.6编写启动类

package com.xidida.mp;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:42
 * @notes
 */
@SpringBootApplication
// 指定扫描mapper路劲
@MapperScan("com.xidida.mp.mapper")
public class MyApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(MyApplication.class, args);
        ConfigurableEnvironment environment = run.getEnvironment();
        String property = environment.getProperty("server.port");
        System.out.println("====================================");
        System.out.println("后台接口:"+"http://127.0.0.1:"+property);
        System.out.println("=====================================");
    }
}

2.3.7编写测试用例

编写UserMapper的测试用例 ,使用UserMapper查询用户列表。
在test下创建测试类,包名为 cn.itcast.mp。

package com.xidida.mp;

import com.xidida.mp.mapper.SystemUserMapper;
import com.xidida.mp.pojo.SystemUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:49
 * @notes 单元测试类
 */
// 测试启动
@RunWith(SpringRunner.class)
// 测试
@SpringBootTest
public class SystemUserTest {

    @Autowired
    private SystemUserMapper userMapper;
    @Test
    public void testSelect(){
        // 查询 SystemUser记录
        List<SystemUser> systemUsers = userMapper.selectList(null);
        System.out.println(systemUsers);
    }
}

效果:
在这里插入图片描述

三、常见配置

在MP中有大量的配置,其中有一部分是Mybatis原生的配置,另一部分是MP的配置,详情:
https://mybatis.plus/config/
下面我们对常用的配置做讲解。

3.1configLocations(配置mybatis-config.xml)

configLocations即MyBatis 配置文件位置,如果您有单独的 MyBatis 配置,请将其路径配置到 configLocation
中。 MyBatis Configuration 的具体内容请参考MyBatis 官方文档
示例:
1 在resources下创建mybatis-config.xml

文件目录为:

resources

​ --mybatis

​ --mybatis-config.xml

<?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>
<!--    <plugins>-->
<!--    <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>-->
<!--   </plugins>-->
</configuration>

2 在application.properties下配置configLocations,如下:

# 指定 mbatis-config.xml 文件路径
mybatis-plus.config-location = classpath:mybatis/mybatis-config.xml

判断是否配置成功:只要运行启动程序,只要没有报错,那么基本就是成功的配置了mybatis-config.xml文件

3.2 mapperLocations(配置mapper文件位置)

3.2.1 mapper 文件位置配置

mapperLocations即MyBatis Mapper 所对应的 mapper配置 文件位置,如果您在 Mapper 中有自定义方法
(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
如果不配置mapperLocations时,mapper的xml文件存放路径需要和mapper class文件保持一致,文件名保持 一
致,如下:

在这里插入图片描述

测试:
新建UserMapper.xml:
将此文件放在resources/com/xidida/mp/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.xidida.mp.mapper.SystemUserMapper">
<!--    注意文件 位置及其名称 com.xidida.mp.mapper.SystemUserMapper -->
<!--
   resultType:返回类型
   parameterType:参数类型
   -->
    <select id="findById" resultType="com.xidida.mp.pojo.SystemUser" parameterType="java.lang.Long">
        select * from system_user where id = #{id}
    </select>
</mapper>

测试用例:

package com.xidida.mp;

import com.xidida.mp.mapper.SystemUserMapper;
import com.xidida.mp.pojo.SystemUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:49
 * @notes 单元测试类
 */
// 测试启动
@RunWith(SpringRunner.class)
// 测试
@SpringBootTest
public class SystemUserTest {
    @Autowired
    private SystemUserMapper userMapper;
    @Test
    public void  testSystemUserfindById(){
        SystemUser byId = userMapper.findById(1L);
        System.out.println(byId);
    }

}

运行结果:

在这里插入图片描述

3.2.2 mapper文件配置到resources文件的其他目录下

也可以给mapper XML文件定义一个和mapper接口不同的存放路径 ,如下:
在这里插入图片描述

# 指定mapper文件的路径  classpath* : 表示只要在classpath 路劲下满足 mybatis/mapper/*xml文件的都加载
mybatis-plus.mapper-locations=classpath*:mybatis/mapper/*xml

Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件

3.3 typeAliasesPackage(别名扫描配置)

设置MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以
直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。

# 别名的映射
mybatis-plus.type-aliases-package=com.xidida.mp.pojo

配置后就不用在xml 文件中配置详细的路径只用配置类名即可:如下:resultType=“SystemUser”

<?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.xidida.mp.mapper.SystemUserMapper">
<!--    注意文件 位置及其名称 com.xidida.mp.mapper.SystemUserMapper -->
<!--
   resultType:返回类型
   parameterType:参数类型
   -->
    <select id="findById" resultType="SystemUser" parameterType="java.lang.Long">
        select * from system_user where id = #{id}
    </select>
</mapper>

3.4 mapUnderscoreToCamelCase(开启自动驼峰)

  • 类型: boolean
  • 默认值: true

是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java
属性名 aColumn(驼峰命名) 的类似映射。

# 开启自动驼峰映射,注意:配置configuration.map‐underscore‐to‐camel‐case则不能配置config‐location
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus:
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定mapper文件的路径  classpath* : 表示只要在classpath 路劲下满足 mybatis/mapper/*xml文件的都加载
  mapper-locations: classpath*:mybatis/mapper/*xml
  # 别名的映射
  type-aliases-package: com.xidida.generator.pojo
<?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>
    <!--    <plugins>-->
    <!--    <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>-->
    <!--   </plugins>-->
    <settings>
        <!--        SQL语句 打印  -->
        <setting name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"/>
    </settings>
</configuration>

注意:
在 MyBatis-Plus 中此属性默认值为true,用于生成最终的 SQL 语句
如果您的数据库命名符合规则无需使用 @TableField 注解指定数据库字段名

测试:

1 屏蔽@TableField

2 测试userMapper.findById方法
跟踪发现userName可以映射成功。

如果项目中有符合驼峰规则的定义也有不符合的,此时建议统一使用@TableField。
3.如果使用mybatis-config.xml的同时在application.properties配置mybatis-plus.configuration则报错
Property ‘configuration’ and ‘configLocation’ can not specified with together
解决方法:
只使用一种配置方法。
本案例屏蔽mybatis-plus.configuration.map-underscore-to-camel-case=true,在mybatis-config.xml中配置
settings。

3.5 log-impl(控制台SQL打印)

3.5.1 properties配置

# 开启控制台打印SQL语句
#mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

注意:当配置了 mybatis-plus.config-location 后其余的 mybatis-plus.configuration.* 配置在yaml文件或properties中配置了就只能在mybatis-config.xml 中配置。

3.5.2 mybatis-config.xml

<?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>
    <!--    <plugins>-->
    <!--    <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>-->
    <!--   </plugins>-->
    <!--
    配置自动驼峰映射 mybatis中默认是 true
    mybatis-plus.configuration.map-underscore-to-camel-case = true
    mapUnderscoreToCamelCase
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"/>
    </settings>
</configuration>

3.6 注意

在这里插入图片描述

在这里插入图片描述

当同时配置了,mybatis-config.xml 文件和 自动驼峰映射的时候只能二选一;

要么保留 : mybatis-plus.config-location = classpath:mybatis/mybatis-config.xml ,自动驼峰在,其配置文件中配置

要么保留:mybatis-plus.configuration.map-underscore-to-camel-case=true

3.5.1 在 mybatis-config.xml 中配置驼峰自动映射

<?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>
    <!--    <plugins>-->
    <!--    <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>-->
    <!--   </plugins>-->
    <!--
    配置自动驼峰映射 mybatis中默认是 true
    mybatis-plus.configuration.map-underscore-to-camel-case = true
    mapUnderscoreToCamelCase
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

四、通用CRUD

通过前面的学习,我们了解到通过继承BaseMapper就可以获取到各种各样的单表操作,接下来我们将详细讲解这
些操作,下图是BaseMapper的各各方法:

在这里插入图片描述

4.1 插入操作

4.1.1 方法定义

/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);

4.1.2 测试用例

package com.xidida.mp;

import com.xidida.mp.mapper.SystemUserMapper;
import com.xidida.mp.pojo.SystemUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:49
 * @notes 单元测试类
 */
// 测试启动
@RunWith(SpringRunner.class)
// 测试
@SpringBootTest
public class SystemUserTest {
    @Autowired
    private SystemUserMapper userMapper;
    @Test
    public void testInsert(){
        SystemUser user =  new SystemUser();
        user.setUserName("zhaoba");
        user.setName("周八");
        user.setAge(26);
        user.setEmail("12311@qq.com");
        user.setPassword("124561");

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-DD HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse("1998-01-01 00:12:12", dateTimeFormatter);

        user.setBirthday(parse);

        int insert = userMapper.insert(user);
        System.out.println(insert);// 返回值 插入数
    }


}

4.1.3 MP主键生成策略

在这里插入图片描述

上例中Mybatis-plus自动生成ID,如何设置id的生成策略呢?
MP支持的id策略如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.baomidou.mybatisplus.annotation;

public enum IdType {
    //数据库ID自增
    AUTO(0),
    //该类型为未设置主键类型
    NONE(1),
    //用户输入ID  <p>该类型可以通过自己注册自动填充插件进行填充</p>
    INPUT(2),
    //全局唯一ID (idWorker) 雪花ID Long类型
    ID_WORKER(3),
    // UUID 
    UUID(4),
    // 雪花 id 字符串类型
    ID_WORKER_STR(5);

    private final int key;

    private IdType(int key) {
        this.key = key;
    }

    public int getKey() {
        return this.key;
    }
}

使用方式就是在

@TableId(value = “id”,type = IdType.ID类型)

1 自增主键:

完全采用数据库自增主键方式。
1)设置mysql数据库主键为自增
2)修改SystemUser对象:

package com.xidida.mp.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:30
 * @notes
 */
@TableName("system_user")// 指定对应的类名
@Data//可以描述:getter、setter等等方法
public class SystemUser {
    /**
     * @TableId
     *      value: 指定组件字段
     *      type: 主键生成策略
     *          IdType.AUTO :自增
     *
     */
    // value="指定主键字段名" type = IdType.AUTO:表示自增
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    @TableField("user_name")// 指定所对应的字段名  字段名是不区分大小写的
    // 当开启你 自动驼峰映射 后就不用在配置指定的字段名
    private String userName;
    @TableField("PASSWORD")
    private String password;
    @TableField("NAME")
    private String name;
    @TableField("AGE")
    private Integer age;
    @TableField("EMAIL")
    private String email;
    @TableField("BIRTHDAY")
    private LocalDateTime birthday;
}

3)程序中不用设置主键

2 输入主键:

手动设置主键值。
1)mysql数据库主键为自增或不是自增都可以
2)修改SystemUser对象:

package com.xidida.mp.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:30
 * @notes
 */
@TableName("system_user")// 指定对应的类名
@Data//可以描述:getter、setter等等方法
public class SystemUser {
    /**
     * @TableId
     *      value: 指定组件字段
     *      type: 主键生成策略
     *          IdType.AUTO :自增
     *          IdType.INPUT: 手动输入
     *          IdType.ID_WORKER: 雪花ID
     *          IdType.UUID: UUID
     *          IdType.ID_WORKER_STR: 雪花id自负歘类型
     *
     *
     */
    // value="指定主键字段名" type = IdType.AUTO:表示自增
    @TableId(value = "id",type = IdType.INPUT)
    private Long id;
    @TableField("user_name")// 指定所对应的字段名  字段名是不区分大小写的
    // 当开启你 自动驼峰映射 后就不用在配置指定的字段名
    private String userName;
    @TableField("PASSWORD")
    private String password;
    @TableField("NAME")
    private String name;
    @TableField("AGE")
    private Integer age;
    @TableField("EMAIL")
    private String email;
    @TableField("BIRTHDAY")
    private LocalDateTime birthday;
}

3)程序中需要设置主键

3 UUID:

生成全局唯一ID。
1)mysql数据库主键为字符串类型,不是自增类型。
2)修改SystemUser对象。

package com.xidida.mp.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:30
 * @notes
 */
@TableName("system_user")// 指定对应的类名
@Data//可以描述:getter、setter等等方法
public class SystemUser {
    /**
     * @TableId
     *      value: 指定组件字段
     *      type: 主键生成策略
     *          IdType.AUTO :自增
     *          IdType.INPUT: 手动输入
     *          IdType.ID_WORKER: 雪花ID
     *          IdType.UUID: UUID
     *          IdType.ID_WORKER_STR: 雪花id自负歘类型
     *
     *
     */
    // value="指定主键字段名" type = IdType.AUTO:表示自增
    @TableId(value = "id",type = IdType.UUID)
    private Long id;
    @TableField("user_name")// 指定所对应的字段名  字段名是不区分大小写的
    // 当开启你 自动驼峰映射 后就不用在配置指定的字段名
    private String userName;
    @TableField("PASSWORD")
    private String password;
    @TableField("NAME")
    private String name;
    @TableField("AGE")
    private Integer age;
    @TableField("EMAIL")
    private String email;
    @TableField("BIRTHDAY")
    private LocalDateTime birthday;
}

3)程序中不用设置主键

4 ID_WORKER_STR:

采用雪花片算法(雪花算法生成的ID是纯数字且具有时间顺序,适合分布式场景)生成全局唯一ID,字符串类型。

1)mysql数据库主键为字符串类型,不是自增类型。
2)修改SystemUser对象。

3)程序中不用设置主键

package com.xidida.mp.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:30
 * @notes
 */
@TableName("system_user")// 指定对应的类名
@Data//可以描述:getter、setter等等方法
public class SystemUser {
    /**
     * @TableId
     *      value: 指定组件字段
     *      type: 主键生成策略
     *          IdType.AUTO :自增
     *          IdType.INPUT: 手动输入
     *          IdType.ID_WORKER: 雪花ID
     *          IdType.UUID: UUID
     *          IdType.ID_WORKER_STR: 雪花id自负歘类型
     *
     *
     */
    // value="指定主键字段名" type = IdType.AUTO:表示自增
    @TableId(value = "id",type = IdType.ID_WORKER_STR)
    private Long id;
    @TableField("user_name")// 指定所对应的字段名  字段名是不区分大小写的
    // 当开启你 自动驼峰映射 后就不用在配置指定的字段名
    private String userName;
    @TableField("PASSWORD")
    private String password;
    @TableField("NAME")
    private String name;
    @TableField("AGE")
    private Integer age;
    @TableField("EMAIL")
    private String email;
    @TableField("BIRTHDAY")
    private LocalDateTime birthday;
}

5 ID_WORKER:
采用雪花片算法生成全局唯一ID,数值类型。
1)mysql数据库主键为数值类型,不是自增类型。
2)修改User对象。

package com.xidida.mp.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:30
 * @notes
 */
@TableName("system_user")// 指定对应的类名
@Data//可以描述:getter、setter等等方法
public class SystemUser {
    /**
     * @TableId
     *      value: 指定组件字段
     *      type: 主键生成策略
     *          IdType.AUTO :自增
     *          IdType.INPUT: 手动输入
     *          IdType.ID_WORKER: 雪花ID
     *          IdType.UUID: UUID
     *          IdType.ID_WORKER_STR: 雪花id自负歘类型
     *
     *
     */
    // value="指定主键字段名" type = IdType.AUTO:表示自增
    @TableId(value = "id",type = IdType.ID_WORKER)
    private Long id;
    @TableField("user_name")// 指定所对应的字段名  字段名是不区分大小写的
    // 当开启你 自动驼峰映射 后就不用在配置指定的字段名
    private String userName;
    @TableField("PASSWORD")
    private String password;
    @TableField("NAME")
    private String name;
    @TableField("AGE")
    private Integer age;
    @TableField("EMAIL")
    private String email;
    @TableField("BIRTHDAY")
    private LocalDateTime birthday;
}

3)程序中不用设置主键

4.2 更新操作

4.2.1 根据id更新

方法定义:

// 更新
int updateById(@Param("et") T entity);

根据id更新操作步骤:
1 首先需要设置对象的主键属性值。
2 再设置要更新的属性值。
3 根据主键找到对象,更新设置属性值。
4 返回影响的记录数。
注意:只能将对象中不为NULL的属性更新到表中。
测试:

package com.xidida.mp;

import com.xidida.mp.mapper.SystemUserMapper;
import com.xidida.mp.pojo.SystemUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:49
 * @notes 单元测试类
 */
// 测试启动
@RunWith(SpringRunner.class)
// 测试
@SpringBootTest
public class SystemUserTest {

    @Autowired
    private SystemUserMapper userMapper;
    @Test
    public void testUpdateById(){
        SystemUser user =  new SystemUser();
        user.setId(1670333395310915585L);
        user.setPassword("456789");
        int i = userMapper.updateById(user);// 返回 更新条数
        System.out.println(i);
    }
}

结果:
在这里插入图片描述

4.2.2 根据条件更新

方法定义:

/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T>
updateWrapper);

根据ID更新一次只能更新一条记录,根据条件更新可实现批量更新。
根据条件更新步骤:
1 在对象中设置要更新的属性值。
2 设置QueryWrapper,设置更新条件,可以设置多个。
3 返回影响的记录数。
注意:只能将对象中不为NULL的属性更新到表中。
测试用例:

// 根据 条件更新
@Test
public void testUpdate(){
    /**
     * 根据密码为 123456 的都将密码更新为 456789
     */
    SystemUser user =  new SystemUser();
    // 设置条件
    user.setPassword("456789");// 更新的值
    // import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    QueryWrapper<SystemUser> qw =new QueryWrapper<>();
    qw.eq("password","123456");// 将字段为 password="123456"
    userMapper.update(user,qw);
}

下次将name等于“曹操”的记录全部更新。

在这里插入图片描述

上边根据id更新 根据条件更新的方法只能将对象中不为NULL的属性更新到表中,下边通过UpdateWrapper进行更
新,将birthday字段更新为NULL。

4.3 删除操作

4.3.1 deleteById

方法定义:

/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);

操作步骤:
1 指定要删除记录的主键值。
2 调用deleteById方法执行删除。
测试用例:

package com.xidida.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xidida.mp.mapper.SystemUserMapper;
import com.xidida.mp.pojo.SystemUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:49
 * @notes 单元测试类
 */
// 测试启动
@RunWith(SpringRunner.class)
// 测试
@SpringBootTest
public class SystemUserTest {
    @Autowired
    private SystemUserMapper userMapper;
    @Test
    public void testDeleteById(){
        /**
         *
         */
        int i = userMapper.deleteById(1670804039043555330L);
        System.out.println(i);
    }

}

结果:
在这里插入图片描述

4.3.2 delete

方法定义:

/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

根据条件删除步骤:
1 定义对象,设置属性值,指定删除条件 ,可指定多个删除条件
注意:删除条件只匹配对象中不为NULL的属性值
2 设置QueryWrapper
3 执行删除

测试用例:

@Test
public void testDelete(){
    //将实体对象进行包装,包装为操作条件
    User user = new User();
	user.setAge(20);
	user.setName("周八");
	QueryWrapper<User> wrapper = new QueryWrapper<>(user);
    int delete = userMapper.delete(qw);
    System.out.println(delete);

}

结果:

在这里插入图片描述

注意:
定义QueryWrapper可以不包装模型对象,手动设置条件,如下:

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("age",20);
wrapper.eq("name","张三");

4.3.3 deleteBatchIds

方法定义:

/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

批量删除操作步骤:
1 指定 id列表
2 执行删除
测试用例:

@Test
public void  testdeleteBatchIds(){
    /**
     * 
     */
    List<Long> list = new ArrayList<>();
    list.add(1670806616757981186L);
    list.add(1670806705685569538L);
    int i = userMapper.deleteBatchIds(list);
    System.out.println(i);
}

结果:
在这里插入图片描述

4.4 查询操作

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

4.4.1 selectById

方法定义:

/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);

根据id查询步骤:
1 设置查询记录的主键值。
2 执行查询。
3 查询结果返回一个对象。
测试用例:

@Test
public void  testselectById(){
    SystemUser user = userMapper.selectById(1670806656608002050L);
    System.out.println(user);
}

结果:
在这里插入图片描述

4.4.2 selectBatchIds

方法定义:

/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

根据id列表查询:
1 设置id列表
2 执行查询
3 查询对象返回List
测试用例:

    @Test
    public void testselectBatchIds(){
        List<SystemUser> systemUsers = userMapper.selectBatchIds(Arrays.asList(1L,2L));
        System.out.println(systemUsers);
    }

结果:
在这里插入图片描述

4.4.3 selectOne

方法定义:

/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

查询步骤:
1 设置QueryWrapper对象,设置查询条件,可以设置多个条件
2 执行查询
注意:如果查询结果为多条记录则报错(TooManyResultsException)。
测试用例:

@Test
public void testSelectOne(){
    /**
     * 只能查询一条 数据;查询多条数据时会报错
     */
    QueryWrapper<SystemUser> qw = new QueryWrapper<>();
    qw.eq("name","张三");
    SystemUser user = userMapper.selectOne(qw);
    System.out.println(user);
}

结果:

在这里插入图片描述

4.4.4 selectCount

方法定义:

/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

测试用例:

@Test
public void testSelectCount(){
    QueryWrapper qw = new QueryWrapper();
    qw.eq("name","周八");
    Integer integer = userMapper.selectCount(qw);
    System.out.println(integer);

}

结果:

在这里插入图片描述

4.4.5 selectList

方法定义:

/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

测试用例:

@Test
public void testSelectList(){
    QueryWrapper<SystemUser> qw = new QueryWrapper();
    qw.ge("age",18);
    List<SystemUser> systemUsers = userMapper.selectList(qw);
    System.out.println(systemUsers);
}

结果:

在这里插入图片描述

4.4.6 selectPage

方法定义:

/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

配置分页插件:

package com.xidida.mp.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/19 23:50
 * @notes  mybatis-plus 分页配置
 */
@Configuration
@MapperScan("com.xidida.mp.mapper")// 需要加上 mapper 扫描路劲
public class MybatisPlusPageConfig {
    /**
     * 配置分页插件的 bean
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

}

测试用例:

package com.xidida.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xidida.mp.mapper.SystemUserMapper;
import com.xidida.mp.pojo.SystemUser;
import lombok.ToString;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/16 23:49
 * @notes 单元测试类
 */
// 测试启动
@RunWith(SpringRunner.class)
// 测试
@SpringBootTest
public class SystemUserTest {

    @Autowired
    private SystemUserMapper userMapper;
    @Test
    public void testSelectPage(){
        QueryWrapper<SystemUser> qw = new QueryWrapper();
        qw.ge("age",18);
        // 参数一: 当前页码,小于1按1算
        // 参数二:每页记录数
        Page<SystemUser> page = new Page<>(1,2);
        //根据条件查询数据
        IPage<SystemUser> iPage = userMapper.selectPage(page, qw);
        System.out.println("数据总条数:" + iPage.getTotal());
        System.out.println("总页数:" + iPage.getPages());
        //取出分页记录
        List<SystemUser> users = iPage.getRecords();
        for (SystemUser user : users) {
            System.out.println("user = " + user);
        }
    }

}

结果:

在这里插入图片描述

五、条件构造器

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

按住 shift 左键,QueryWrapper==》 AbstractWrapper ==》Wrapper
在这里插入图片描述

在MP查询中,还可以使用lambda方式查询,降低数据库列表写错的风险。

5.1 基本比较操作

eq
等于 =
ne
不等于 <>
gt
大于 >
ge
大于等于 >=
lt
小于 <
le
小于等于 <=
between
BETWEEN 值1 AND 值2
notBetween
NOT BETWEEN 值1 AND 值2
in
字段 IN (value.get(0), value.get(1), …)
notIn
字段 NOT IN (v0, v1, …)

测试用例:

@Test
    public void test(){
        QueryWrapper<SystemUser> qw = new QueryWrapper<>();
        qw.ge("age",30); //age>=30
        qw.le("age",36);// age<=36
        //qw.between("age",30,36);//
        List<SystemUser> systemUsers = userMapper.selectList(qw);
        System.out.println(systemUsers);

    }
==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE age >= ? AND age <= ? AND name BETWEEN ? AND ? 
==> Parameters: 30(Integer), 36(Integer), 赵六(String), 周八(String)
<==      Total: 0

Lambda方式构造条件:

@Test
public void testLambda(){
    LambdaQueryWrapper<SystemUser> qw = new LambdaQueryWrapper();
    qw.eq(SystemUser::getName,"周八");
    qw.ge(SystemUser::getAge,30);
    qw.le(SystemUser::getAge,36);
    List<SystemUser> systemUsers = userMapper.selectList(qw);
    System.out.println(systemUsers);
}
==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE NAME = ? AND AGE >= ? AND AGE <= ? 
==> Parameters: 周八(String), 30(Integer), 36(Integer)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 3

通常在开发中要根据表达式进行判断,表达式为true则拼接条件,如下:

@Test
public void testLambda(){
    LambdaQueryWrapper<SystemUser> qw = new LambdaQueryWrapper();
    String name = "周八";
    // 增加不等于空拼装条件
    qw.eq(name!=null && !name.equals("") , SystemUser::getName,name);
    qw.ge(SystemUser::getAge,30);
    qw.le(SystemUser::getAge,36);
    List<SystemUser> systemUsers = userMapper.selectList(qw);
    System.out.println(systemUsers);
}

结果:

==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE NAME = ? AND AGE >= ? AND AGE <= ? 
==> Parameters: 周八(String), 30(Integer), 36(Integer)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 3

5.2 模糊查询

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 ‘王%’
测试用例:

@Test
public void testLike(){
    // like
    QueryWrapper<SystemUser> qw =new QueryWrapper<>();
    qw.like("user_name","z");
    List<SystemUser> systemUsers = userMapper.selectList(qw);
    System.out.println("like==^");
    System.out.println(systemUsers);
    // **notLike**
    qw = new QueryWrapper<>();
    qw.notLike("user_name","z");
    List<SystemUser> systemUsers1 = userMapper.selectList(qw);
    System.out.println("notLike==^");
    System.out.println(systemUsers1);
    // likeLeft
    qw =new QueryWrapper<>();
    qw.likeLeft("user_name","z");
    List<SystemUser> systemUsers2 = userMapper.selectList(qw);
    System.out.println("likeLeft==^");
    System.out.println(systemUsers2);
    //likeRight
    qw = new QueryWrapper<>();
    qw.likeRight("user_name","z");
    List<SystemUser> systemUsers3 = userMapper.selectList(qw);
    System.out.println("likeRight==^");
    System.out.println(systemUsers3);
}
==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE user_name LIKE ? 
==> Parameters: %z%(String)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1, zhangsan, 456789, 张三, 18, 1234@qq.com, 2023-06-16 23:14:36
<==        Row: 4, zhaoliu, 456789, 赵六, 30, 1237@qq.com, 2023-06-16 23:15:45
<==        Row: 1670806451988918273, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806550127222785, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806656608002050, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151006990872578, zhaoba, 124561, 周八, 27, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007720681473, zhaoba, 124561, 周八, 28, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008362409986, zhaoba, 124561, 周八, 37, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008572125185, zhaoba, 124561, 周八, 42, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008714731521, zhaoba, 124561, 周八, 48, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008861532161, zhaoba, 124561, 周八, 55, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009012527105, zhaoba, 124561, 周八, 63, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009167716354, zhaoba, 124561, 周八, 72, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 16
like==^

==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE user_name NOT LIKE ? 
==> Parameters: %z%(String)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 2, lisi, 456789, 李四, 19, 1235@qq.com, 2023-06-17 23:15:03
<==        Row: 3, wangwu, 456789, 王五, 20, 1236@qq.com, 2023-06-16 23:15:28
<==        Row: 5, sunqi, 456789, 孙七, 22, 1238@qq.com, 2023-06-16 23:16:04
<==      Total: 3
notLike==^
    
[SystemUser(id=2, userName=lisi, password=456789, name=李四, age=19, email=1235@qq.com, birthday=2023-06-17T23:15:03), SystemUser(id=3, userName=wangwu, password=456789, name=王五, age=20, email=1236@qq.com, birthday=2023-06-16T23:15:28), SystemUser(id=5, userName=sunqi, password=456789, name=孙七, age=22, email=1238@qq.com, birthday=2023-06-16T23:16:04)]

==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE user_name LIKE ? 
==> Parameters: %z(String)
<==      Total: 0
likeLeft==^
 
==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE user_name LIKE ? 
==> Parameters: z%(String)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1, zhangsan, 456789, 张三, 18, 1234@qq.com, 2023-06-16 23:14:36
<==        Row: 4, zhaoliu, 456789, 赵六, 30, 1237@qq.com, 2023-06-16 23:15:45
<==        Row: 1670806451988918273, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806550127222785, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806656608002050, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151006990872578, zhaoba, 124561, 周八, 27, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007720681473, zhaoba, 124561, 周八, 28, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008362409986, zhaoba, 124561, 周八, 37, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008572125185, zhaoba, 124561, 周八, 42, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008714731521, zhaoba, 124561, 周八, 48, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008861532161, zhaoba, 124561, 周八, 55, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009012527105, zhaoba, 124561, 周八, 63, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009167716354, zhaoba, 124561, 周八, 72, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 16
likeRight==^

Lambda方式构造条件:

@Test
public void testLike(){
    // like
    LambdaQueryWrapper<SystemUser> qw =new LambdaQueryWrapper<>();
    qw.like(SystemUser::getUserName,"z");
    List<SystemUser> systemUsers = userMapper.selectList(qw);
    System.out.println("like==》");
    System.out.println(systemUsers);
    // **notLike**
    qw = new LambdaQueryWrapper<>();
    qw.like(SystemUser::getUserName,"z");
    List<SystemUser> systemUsers1 = userMapper.selectList(qw);
    System.out.println("notLike==>");
    System.out.println(systemUsers1);
    // likeLeft
    qw =new LambdaQueryWrapper<>();
    qw.like(SystemUser::getUserName,"z");
    List<SystemUser> systemUsers2 = userMapper.selectList(qw);
    System.out.println("likeLeft==>");
    System.out.println(systemUsers2);
    //likeRight
    qw = new LambdaQueryWrapper<>();
    qw.like(SystemUser::getUserName,"z");
    List<SystemUser> systemUsers3 = userMapper.selectList(qw);
    System.out.println("likeRight==>");
    System.out.println(systemUsers3);
}

5.3 逻辑查询

or
拼接 OR
主动调用 or 表示紧接着下一个方法不是用 and 连接!(不调用 or 则默认为使用 and 连接)
and
AND 嵌套
例: and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”)) —> and (name = ‘李白’ and status <>‘活着’)

测试用例

@Test
public void testOr2(){
    QueryWrapper<SystemUser> lqw = new QueryWrapper<>();
    lqw.eq("name","张三").or().eq("name","李四");
    Page<SystemUser> page = new Page<>(1,10);
    IPage<SystemUser> systemUserIPage = userMapper.selectPage(page, lqw);
    System.out.println(systemUserIPage);
}

Lambda方式构造条件:

@Test
public void testOr(){
    LambdaQueryWrapper<SystemUser> lqw = new LambdaQueryWrapper<>();
    lqw.eq(SystemUser::getName,"张三").or().eq(SystemUser::getName,"李四");
    Page<SystemUser> page = new Page<>(1,10);
    IPage<SystemUser> systemUserIPage = userMapper.selectPage(page, lqw);
    System.out.println(systemUserIPage);
}
==>  Preparing: SELECT COUNT(1) FROM system_user WHERE NAME = ? OR NAME = ? 
==> Parameters: 张三(String), 李四(String)
<==    Columns: COUNT(1)
<==        Row: 2
==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE NAME = ? OR NAME = ? LIMIT ?,? 
==> Parameters: 张三(String), 李四(String), 0(Long), 10(Long)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1, zhangsan, 456789, 张三, 18, 1234@qq.com, 2023-06-16 23:14:36
<==        Row: 2, lisi, 456789, 李四, 19, 1235@qq.com, 2023-06-17 23:15:03
<==      Total: 2

5.4 select(只查询部分字段)

在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。

@Test
public void testSelect4(){
    /**
     * 只查询其中的某几个字段
     */
    QueryWrapper<SystemUser> lqw = new QueryWrapper();
    lqw.eq("name","张三");
    lqw.select("id","name");
    Page<SystemUser> page = new Page<>(1,10);
    IPage<SystemUser> systemUserIPage = userMapper.selectPage(page, lqw);
    System.out.println(systemUserIPage);
}

Lambda方式构造条件:

@Test
public void testSelect3(){
    /**
     * 只查询其中的某几个字段
     */
    LambdaQueryWrapper<SystemUser> lqw = new LambdaQueryWrapper();
    lqw.eq(SystemUser::getName,"张三");
    lqw.select(SystemUser::getUserName,SystemUser::getId);
    Page<SystemUser> page = new Page<>(1,10);
    IPage<SystemUser> systemUserIPage = userMapper.selectPage(page, lqw);
    System.out.println(systemUserIPage);
}
==>  Preparing: SELECT COUNT(1) FROM system_user WHERE NAME = ? 
==> Parameters: 张三(String)
<==    Columns: COUNT(1)
<==        Row: 1
==>  Preparing: SELECT user_name,id FROM system_user WHERE NAME = ? LIMIT ?,? 
==> Parameters: 张三(String), 0(Long), 10(Long)
<==    Columns: user_name, id
<==        Row: zhangsan, 1
<==      Total: 1

5.5 排序

orderByAsc
升序排序
参数:变长数组,设置多个字段名
例: orderByAsc(“id”, “name”) —> order by id ASC,name ASC

orderByDesc
降序排序
参数:变长数组,设置多个字段名
例: orderByDesc(“id”, “name”) —> order by id DESC,name DESC

orderBy

orderBy(boolean condition, boolean isAsc, R... columns)
‐ 自定义排序规则
‐ 参数1:true有效,false无效 ,参数2:是否升序,参数3..设置多个字段
‐ 例: `orderBy(true, true, "id", "name")`‐‐‐>`order by id ASC,name ASC`
‐ 也可以多个orderBy拼装,如下:
orderBy(true, true, "id").orderBy(true, true, "name") 效果同上
例子:

Lambda方式构造条件:

@Test
public void testOrBy(){
    LambdaQueryWrapper<SystemUser> lqw = new LambdaQueryWrapper<>();
    // 降序 orderByDesc
    lqw.eq(SystemUser::getName,"周八");
    lqw.orderByDesc(SystemUser::getId);
    List<SystemUser> systemUsers = userMapper.selectList(lqw);
    System.out.println(systemUsers);
    // 升序
    lqw = new LambdaQueryWrapper<>();
    lqw.eq(SystemUser::getName,"周八");
    lqw.orderByAsc(SystemUser::getId);
    systemUsers = userMapper.selectList(lqw);
    System.out.println(systemUsers);
    // **orderBy** 自定义升序还是降序
    lqw = new LambdaQueryWrapper<>();
    lqw.eq(SystemUser::getName,"周八");
    lqw.orderBy(true,true,SystemUser::getId);
    systemUsers = userMapper.selectList(lqw);
    System.out.println(systemUsers);
}
==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE NAME = ? ORDER BY id DESC 
==> Parameters: 周八(String)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1671151009167716354, zhaoba, 124561, 周八, 72, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009012527105, zhaoba, 124561, 周八, 63, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008861532161, zhaoba, 124561, 周八, 55, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008714731521, zhaoba, 124561, 周八, 48, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008572125185, zhaoba, 124561, 周八, 42, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008362409986, zhaoba, 124561, 周八, 37, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007720681473, zhaoba, 124561, 周八, 28, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151006990872578, zhaoba, 124561, 周八, 27, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806656608002050, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806550127222785, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806451988918273, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 14


==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE NAME = ? ORDER BY id ASC 
==> Parameters: 周八(String)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1670806451988918273, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806550127222785, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806656608002050, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151006990872578, zhaoba, 124561, 周八, 27, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007720681473, zhaoba, 124561, 周八, 28, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008362409986, zhaoba, 124561, 周八, 37, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008572125185, zhaoba, 124561, 周八, 42, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008714731521, zhaoba, 124561, 周八, 48, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008861532161, zhaoba, 124561, 周八, 55, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009012527105, zhaoba, 124561, 周八, 63, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009167716354, zhaoba, 124561, 周八, 72, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 14

==>  Preparing: SELECT id,user_name,PASSWORD,NAME,AGE,EMAIL,BIRTHDAY FROM system_user WHERE NAME = ? ORDER BY id ASC 
==> Parameters: 周八(String)
<==    Columns: id, user_name, PASSWORD, NAME, AGE, EMAIL, BIRTHDAY
<==        Row: 1670806451988918273, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806550127222785, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1670806656608002050, zhaoba, 124561, 周八, 26, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671150670200877057, zhaoba, 124561, 周八, 31, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151006990872578, zhaoba, 124561, 周八, 27, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007720681473, zhaoba, 124561, 周八, 28, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151007909425153, zhaoba, 124561, 周八, 30, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008156889089, zhaoba, 124561, 周八, 33, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008362409986, zhaoba, 124561, 周八, 37, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008572125185, zhaoba, 124561, 周八, 42, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008714731521, zhaoba, 124561, 周八, 48, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151008861532161, zhaoba, 124561, 周八, 55, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009012527105, zhaoba, 124561, 周八, 63, 12311@qq.com, 1998-01-01 00:12:12
<==        Row: 1671151009167716354, zhaoba, 124561, 周八, 72, 12311@qq.com, 1998-01-01 00:12:12
<==      Total: 14

六、代码生成器(简单)

也可以使用 插件完成

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Mapper接口、 Entity实体类
及Mapper XML文件、 Service 、Controller 等各个模块的代码,极大的提升了开发效率。

6.1在pom文件中引入依赖

<!--       模板引擎  -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>
<!--     mybatis-plus 代码生成器依赖     -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.1.0</version>
</dependency>

6.2 获取官方案例

6.3 测试

这里使用提供的生成器工程,解压generator.zip,并导入IDEA。

package com.xidida.mp.generator;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
 * @author YJC
 * @e-mail xiaochun235@qq.com
 * @Date 2023/6/20 22:39
 * @notes
 */
/**
 * <p>
 * MyBatis Plus Generator 配置执行类示例
 * </p>
 *
 * @author
 * @since
 */
public class MyBatisPlusGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        //当前项目名
        String projectName = "/generator";

        globalConfig.setOutputDir(projectPath + projectName+"/src/main/java");
        globalConfig.setAuthor("author");
        globalConfig.setOpen(false);
        globalConfig.setIdType(IdType.ID_WORKER);
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据源配置 需配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();


        // 交易服务
        dataSourceConfig
                .setUrl("jdbc:mysql://127.0.0.1:3306/mybatis_plus_demo?serverTimezone=Asia/Shanghai");
        // dataSourceConfig.setSchemaName("public");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        autoGenerator.setDataSource(dataSourceConfig);

        // 生成包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.xidida");
        //如果需要手动输入模块名
        packageConfig.setModuleName(scanner("模块名"));
        autoGenerator.setPackageInfo(packageConfig);

        // 自定义配置
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名
                return projectPath + projectName+"/src/main/resources/mapper/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        injectionConfig.setFileOutConfigList(focList);
        autoGenerator.setCfg(injectionConfig);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity-test.java");
        // templateConfig.setService("templates/service.java");
        // templateConfig.setController("templates/controller.java");

        templateConfig.setXml(null);
        autoGenerator.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);//表名映射到实体策略,带下划线的转成驼峰
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);//列名映射到类型属性策略,带下划线的转成驼峰
        // strategyConfig.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
        strategyConfig.setEntityLombokModel(true);//实体类使用lombok
//        strategyConfig.setRestControllerStyle(true);
        // strategyConfig.setSuperControllerClass("com.baomidou.ant.common.BaseController");

        // 如果 setInclude() //设置表名不加参数, 会自动查找所有表
        // 如需要制定单个表, 需填写参数如: strategyConfig.setInclude("user_info);
        strategyConfig.setInclude();
        // strategyConfig.setSuperEntityColumns("id");
//        strategyConfig.setControllerMappingHyphenStyle(true);

        //自动将数据库中表名为 user_info 格式的转为 UserInfo 命名
        strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");//表名映射到实体名称去掉前缀
        strategyConfig.setEntityBooleanColumnRemoveIsPrefix(true);// Boolean类型字段是否移除is前缀处理
        autoGenerator.setStrategy(strategyConfig);
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        System.out.println("===================== MyBatis Plus Generator ==================");

        autoGenerator.execute();

        System.out.println("================= MyBatis Plus Generator Execute Complete ==================");
    }

}

运行MyBatisPlusGenerator的main方法。
输入模块名:
注意:模块名匹配表名前缀会自动去掉,否则生成的模型类保留前缀。

在这里插入图片描述

生成的文件包括entity、controller、service、mapper,如下:

在这里插入图片描述

6.4 自定义模板

上边的自动生成代码是通过freemarker 引擎生成代码,可以通过自定义freemarker模板对生成代码进行个性化定
义。
在resources下创建templates目录,目录下放入要个性化定义模板即可。
具体模板参考资料文件夹下的templates目录 。

配置模板
TemplateConfig templateConfig = new TemplateConfig();

    // 配置自定义输出模板
    //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
    // templateConfig.setEntity("templates/entity-test.java");
    // templateConfig.setService("templates/service.java");
    // templateConfig.setController("templates/controller.java");

    templateConfig.setXml(null);
    autoGenerator.setTemplate(templateConfig);

    // 策略配置
    StrategyConfig strategyConfig = new StrategyConfig();
    strategyConfig.setNaming(NamingStrategy.underline_to_camel);//表名映射到实体策略,带下划线的转成驼峰
    strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);//列名映射到类型属性策略,带下划线的转成驼峰
    // strategyConfig.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
    strategyConfig.setEntityLombokModel(true);//实体类使用lombok

// strategyConfig.setRestControllerStyle(true);
// strategyConfig.setSuperControllerClass(“com.baomidou.ant.common.BaseController”);

    // 如果 setInclude() //设置表名不加参数, 会自动查找所有表
    // 如需要制定单个表, 需填写参数如: strategyConfig.setInclude("user_info);
    strategyConfig.setInclude();
    // strategyConfig.setSuperEntityColumns("id");

// strategyConfig.setControllerMappingHyphenStyle(true);

    //自动将数据库中表名为 user_info 格式的转为 UserInfo 命名
    strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");//表名映射到实体名称去掉前缀
    strategyConfig.setEntityBooleanColumnRemoveIsPrefix(true);// Boolean类型字段是否移除is前缀处理
    autoGenerator.setStrategy(strategyConfig);
    autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
    System.out.println("===================== MyBatis Plus Generator ==================");

    autoGenerator.execute();

    System.out.println("================= MyBatis Plus Generator Execute Complete ==================");
}

}


运行MyBatisPlusGenerator的main方法。
输入模块名:
注意:模块名匹配表名前缀会自动去掉,否则生成的模型类保留前缀。

[外链图片转存中...(img-h8Y4IkdV-1687359218839)]

生成的文件包括entity、controller、service、mapper,如下:

[外链图片转存中...(img-ASKXpEPL-1687359218840)]

## 6.4 自定义模板

上边的自动生成代码是通过freemarker 引擎生成代码,可以通过自定义freemarker模板对生成代码进行个性化定
义。
在resources下创建templates目录,目录下放入要个性化定义模板即可。
具体模板参考资料文件夹下的templates目录 。

# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值