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

完美!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM