mybatis-plus自动生成代码

1.背景

本教程将介绍如何使用 mybatis-plus 工具自动给我们生成 Controller、Service、Entity、Mapper、Mapper.xml 层代码;

给出一个便于于学习理解的的最基础版本,

同时为了便于大家快速在实际生产同时也给出一个更符合生产使用的生产版本,

在这个版本中会有常用的框架整合,

比如框架中使用了

自定义模板、

自定义mapper基类、

自定义service基类、

自定义controller基类、

生成的代码默认单表的CRUD接口已全部实现、

整合了swagger接口文档、

日志输出等......

2.生成代码结构如下

demo环境:

 实际生产:

 启动项目swagger文档:

3.简单demo实现

步骤一:数据库表准备

CREATE TABLE `sys_user` (
  `id` int(32) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(64) DEFAULT NULL,
  `parent_id` int(32) DEFAULT NULL COMMENT '领导id',
  `version` int(64) DEFAULT NULL,
  `gender` int(32) DEFAULT NULL,
  `age` int(32) DEFAULT NULL,
  `position` varchar(64) DEFAULT NULL,
  `account` varchar(255) DEFAULT NULL,
  `we_chat` varchar(255) DEFAULT NULL,
  `password` varchar(225) DEFAULT NULL,
  `status` varchar(64) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL COMMENT '类型',
  `update_time` datetime DEFAULT NULL,
  `deleted` int(255) DEFAULT '0' COMMENT '逻辑删除字段:0-没有删除,1-已删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4;
View Code

步骤二:构建maven项目

步骤三:pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ldp.mpGenerator</groupId>
    <artifactId>mp-generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mp-generator</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <!-- springmvc容器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!-- druid链接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--代码生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- velocity 模板 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <!-- 多功能工具类 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <!-- xml放在java目录下-->
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--指定资源的位置(xml放在resources下,可以不用指定)-->
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>

</project>
View Code

步骤四:启动文件配置

# 配置端口
server:
  port: 8080
  servlet:
    context-path: /api

spring:
  # 配置数据源
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp-data?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&
    username: root
    password: admin

# mybatis-plus相关配置
mybatis-plus:
  # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
  mapper-locations: classpath:mapper/*.xml
  # 以下配置均有默认值,可以不设置
  global-config:
    db-config:
      #主键类型 AUTO:"数据库ID自增" INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
      id-type: auto
      #字段策略 IGNORED:"忽略判断"  NOT_NULL:"非 NULL 判断")  NOT_EMPTY:"非空判断"
      insertStrategy: NOT_EMPTY
      updateStrategy: NOT_EMPTY
  configuration:
    # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
    map-underscore-to-camel-case: true
    # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
    call-setters-on-nulls: true
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

logging:
  config: classpath:logback.xml
View Code

步骤五:自动代码工具类

package com.ldp.mpgenerator;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.List;

/**
 * @Copyright (C) XXXXXXX科技有限公司
 * @Author: LI DONG PING
 * @Date: 2020-10-14 13:09
 * @Description:
 */
public class AutoGeneratorUtil {
    /**
     * 启动生成代码
     *
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("------开始---------");
        doGenerator();
        System.out.println("------结束---------");
    }

    /**
     * 基础配置
     */
    private static String outputDir = System.getProperty("user.dir") + "/src/main/java";
    private static String author = "lidongping";
    /**
     * 数据库配置
     */
    private static DbType dbType = DbType.MYSQL;
    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String userName = "root";
    private static String password = "admin";
    private static String url = "jdbc:mysql://localhost:3306/mp-data?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&";
    private static String[] tables = {"sys_user"};
    /**
     * 生成包路径
     */
    private static String packageParent = "com.ldp.mpgenerator";
    private static String entity = "sys.entity";
    private static String mapper = "sys.mapper";
    private static String mapperXml = "sys.mapper.mappers";
    private static String service = "sys.service";
    private static String serviceImpl = "sys.service.impl";
    private static String controller = "sys.controller";

    public static void doGenerator() {
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //代码生成存放位置
        gc.setOutputDir(outputDir);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);
        gc.setEnableCache(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(false);
        gc.setOpen(true);
        gc.setAuthor(author);
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceImplName("%sService");
        gc.setServiceName("I%sService");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(dbType);
        dsc.setDriverName(driverName);
        dsc.setUsername(userName);
        dsc.setPassword(password);
        dsc.setUrl(url);
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(tables);
        strategy.setSuperEntityColumns(new String[]{});
        //strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
        List<TableFill> tableFillList = CollUtil.newArrayList();
        TableFill fill = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        tableFillList.add(fill);
        fill = new TableFill("create_time", FieldFill.INSERT);
        tableFillList.add(fill);
        strategy.setTableFillList(tableFillList);
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageParent);
        // 代码生成包路径
        pc.setEntity(entity);
        pc.setMapper(mapper);
        pc.setXml(mapperXml);
        pc.setService(service);
        pc.setServiceImpl(serviceImpl);
        pc.setController(controller);
        mpg.setPackageInfo(pc);
        // 注入自定义配置,可以在 VM 中使用 ${cfg.packageMy} 设置值
        // InjectionConfig cfg = new InjectionConfig() {
        //     public void initMap() {
        //         Map<String, Object> map = new HashMap<String, Object>();
        //         map.put("packageMy", packageBase);
        //         this.setMap(map);
        //     }
        // };

        // mpg.setCfg(cfg);

        // TemplateConfig tc = new TemplateConfig();
        // tc.setEntity("templates/entity.java.vm");
        // tc.setMapper("templates/mapper.java.vm");
        // tc.setXml("templates/mapper.xml.vm");
        // tc.setServiceImpl("templates/serviceImpl.java.vm");
        // tc.setService("templates/service.java.vm");
        // tc.setController("templates/controller.java.vm");
        // mpg.setTemplate(tc);
        // 执行生成
        mpg.execute();
    }
}
View Code

第六步:执行生产自动代码

4.实际生产案例

构建步骤与上面的思路一致,只是多了一些封装等,具体代码过多,请自己下载

5.代码下载

mybatis-plus系统化学习教程:https://www.cnblogs.com/newAndHui/p/14141950.html

完美!

原文地址:https://www.cnblogs.com/newAndHui/p/14136665.html