Mybatis——》mybatis-plus-generator代码生成器

推荐链接:
    总结——》【Java】
    总结——》【Mysql】
    总结——》【Spring】
    总结——》【SpringBoot】
    总结——》【MyBatis、MyBatis-Plus】

https://gitee.com/xiaoxianwansui/springboot-mybatisplus-generator

一、数据库

/*
    Schema:test
    Info:测试数据库
    Date:2022/09/07 13:49:38
*/
-- 1、创建数据库
CREATE
DATABASE `xiaoxian` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

-- 2、创建表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
    `id`          bigint   NOT NULL AUTO_INCREMENT,
    `name`        varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
    `version`     int      NOT NULL                                      DEFAULT '0' COMMENT '乐观锁版本号',
    `is_delete`   tinyint(1) NOT NULL DEFAULT '0' COMMENT '逻辑删除标识1:已删除,0:未删除',
    `create_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '创建用户',
    `create_time` datetime NOT NULL                                      DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` datetime NOT NULL                                      DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `update_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '更新用户',
    PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;

-- 3、插入数据
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
                               `update_user`)
VALUES (1, '赵', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
                               `update_user`)
VALUES (2, '钱', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
                               `update_user`)
VALUES (3, '孙', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
                               `update_user`)
VALUES (4, '李', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');

二、项目结构

在这里插入图片描述

三、添加pom依赖

<?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.7.1</version>
    <relativePath/>
  </parent>
  <groupId>com.xiaoxian</groupId>
  <artifactId>mybatisplus-generator</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>generator</name>
  <description>springboot-mybatisplus-generator</description>
  <properties>
    <java.version>1.8</java.version>
    <druid.version>1.1.22</druid.version>
    <mybatis.plus.version>3.4.1</mybatis.plus.version>
    <!--        <mybatis.plus.version>3.5.1</mybatis.plus.version>-->
    <guava.version>28.2-jre</guava.version>
    <knife4j.version>2.0.8</knife4j.version>
    <fastjson.version>1.2.70</fastjson.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>${druid.version}</version>
    </dependency>
    <!-- mybatis-plus start-->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>${mybatis.plus.version}</version>
    </dependency>

    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>
      <version>${mybatis.plus.version}</version>
    </dependency>
    <!-- mybatis-plus generator start-->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-generator</artifactId>
      <version>${mybatis.plus.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity-engine-core</artifactId>
      <version>2.2</version>
    </dependency>

    <!--test start-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <!--lombok start-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

      <!-- swagger start -->
      <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>
      <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>knife4j-spring-boot-starter</artifactId>
      <version>${knife4j.version}</version>
    </dependency>
      <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>knife4j-aggregation-spring-boot-starter</artifactId>
      <version>${knife4j.version}</version>
    </dependency>

      <!--fastjson start-->
      <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>
    </dependencies>

      <build>

    </build>

    </project>

四、创建代码生成器类

1、3.5.1以下版本

<mybatis.plus.version>3.4.1</mybatis.plus.version>


package com.xiaoxian.mybatisplusgenerator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
    public class CodeGenerator {

        public static void generator(String projectPath, String projectName, String modulename, String mysqlUrl, String username, String password, String tableNams, String tablePrefix,
                                     String superEntityClass) {
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();

            modulename = modulename == null ? "" : modulename;
            // 全局配置
            GlobalConfig gc = new GlobalConfig();

            gc.setOutputDir("/src/main/java");

            gc.setFileOverride(true);
            gc.setActiveRecord(true);
            gc.setEnableCache(false);// XML 二级缓存
            gc.setBaseResultMap(true);// XML ResultMap
            gc.setBaseColumnList(true);// XML columList

            gc.setAuthor("xiaoxian");
            gc.setOpen(false);
            gc.setSwagger2(true);
            mpg.setGlobalConfig(gc);

            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://" + mysqlUrl + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false");
            dsc.setDriverName("com.mysql.jdbc.Driver");
            dsc.setUsername(username);
            dsc.setPassword(password);
            mpg.setDataSource(dsc);

            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(modulename);
            pc.setParent("com.xiaoxian." + projectName);
            pc.setEntity("entity");
            pc.setXml("mapper");
            pc.setMapper("mapper");
            pc.setService("service");
            pc.setServiceImpl("service.impl");
            pc.setController("controller");

            Map<String, String> map = new HashMap();
            map.put(ConstVal.ENTITY_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/entity");
            map.put(ConstVal.SERVICE_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/service");
            map.put(ConstVal.SERVICE_IMPL_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + projectName + "/" + modulename + "/service/impl");
            map.put(ConstVal.MAPPER_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/mapper");
            map.put(ConstVal.XML_PATH, projectPath + "/src/main/resources/mapper");
                    map.put(ConstVal.CONTROLLER_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/controller");

                    pc.setPathInfo(map);
                    mpg.setPackageInfo(pc);

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

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

                    // 自定义输出配置
                    List<FileOutConfig> focList = new ArrayList<>();
                    // 自定义配置会被优先输出
                    focList.add(new FileOutConfig(templatePath) {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "/src/main/resources/mapper/"
                    + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                    }
                    });

                    cfg.setFileCreate(new IFileCreate() {
                    @Override
                    public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                    // 判断自定义文件夹是否需要创建
                    checkDir(filePath);
                    if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                    }
                    // 允许生成模板文件
                    return true;
                    }
                    });

                    cfg.setFileOutConfigList(focList);
                    mpg.setCfg(cfg);

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

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

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

                    // 策略配置
                    StrategyConfig strategy = new StrategyConfig();
                    strategy.setNaming(NamingStrategy.underline_to_camel);
                    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
                    strategy.setSuperEntityClass(superEntityClass);
                    strategy.setEntityLombokModel(true);
                    strategy.setRestControllerStyle(true);

                    // 公共父类
                    //        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
                    // 写于父类中的公共字段

                    strategy.setSuperEntityColumns("id", "version", "is_delete", "create_time", "update_time", "update_user", "create_user");
                    strategy.setInclude(tableNams.split(","));
                    strategy.setControllerMappingHyphenStyle(true);
                    strategy.setTablePrefix(tablePrefix);
                    mpg.setStrategy(strategy);
                    //        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
                    mpg.execute();
                    }

                    public static void main(String[] args) {
                    //生成在当前项目路径
                    String projectPath = System.getProperty("user.dir");
                    generator(
                    projectPath,
                    "mybatisplusgenerator",
                    "",
                    "127.0.0.1:3306/test",
                    "root",
                    "123456",
                    "user",
                    "t_",
                    "com.xiaoxian.mybatisplusgenerator.common.BaseEntity"
                    );
                    }

                    }


2、3.5.1 及其以上版本

<mybatis.plus.version>3.5.1</mybatis.plus.version>

package com.xiaoxian.mybatisplusgenerator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
    public class CodeGeneratorNew {

        public static void generator(String projectPath, String projectName, String modulename, String mysqlUrl, String username, String password, String tableNams, String tablePrefix,
                                     String superEntityClass) {

            String javaDir = projectPath + "/src/main/java";
            String resourcesDir = projectPath + "/src/main/resources";

            Map<OutputFile, String> map = new HashMap();

            map.put(OutputFile.entity, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/entity");
            map.put(OutputFile.service, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/service");
            map.put(OutputFile.serviceImpl, javaDir + "/com/xiaoxian/" + projectName + "/" + modulename + "/service/impl");
            map.put(OutputFile.mapper, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/mapper");
            map.put(OutputFile.mapperXml, resourcesDir + "/mapper");
            map.put(OutputFile.controller, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/controller");


            FastAutoGenerator.create("jdbc:mysql://" + mysqlUrl + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false", username, password)
                .globalConfig(builder -> {
                    builder.author("xiaoxiao") // 设置作者
                        .enableSwagger() // 开启 swagger 模式
                        .fileOverride() // 覆盖已生成文件
                        .outputDir(javaDir); // 指定输出目录
                })

                .packageConfig(builder -> {
                    builder.parent("com.xiaoxian.mybatisplusgenerator") // 设置父包名
                        .entity("entity")
                        .mapper("mapper")
                        .moduleName("") // 设置父包模块名
                        .pathInfo(map); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("user") // 设置需要生成的表名
                        .addTablePrefix("cms_", "c_") // 设置过滤表前缀
                        .entityBuilder().enableLombok().enableChainModel().enableActiveRecord().superClass(superEntityClass)
                        ;
                })
                //                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

        }

        public static void main(String[] args) {
            //生成在当前项目路径
            String projectPath = System.getProperty("user.dir");
            generator(
                projectPath,
                "mybatisplusgenerator",
                "",
                "127.0.0.1:3306/xiaoxian",
                "root",
                "123456",
                "user",
                "t_",
                "com.xiaoxian.mybatisplusgenerator.common.BaseEntity"
                );
                }

                }

五、执行main方法

在这里插入图片描述

六、测试

package com.xiaoxian.mybatisplusgenerator;

import com.xiaoxian.mybatisplusgenerator.service.IUserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ApplicationTests {

    @Autowired
    IUserService userService;

    @Test
    void list() {
        System.out.println(userService.list());
    }
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值