MyBatisPlus最新的3.5.2以上的代码生成器

发布时间:2023年12月19日

MyBatisPlus最新的3.5.2以上的代码生成器

官网:https://baomidou.com/pages/779a6e/#%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8

1.maven依赖

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

快速生成

FastAutoGenerator.create("url", "username", "password")
    .globalConfig(builder -> {
        builder.author("baomidou") // 设置作者
            .enableSwagger() // 开启 swagger 模式
            .fileOverride() // 覆盖已生成文件
            .outputDir("D://"); // 指定输出目录
    })
    .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
        int typeCode = metaInfo.getJdbcType().TYPE_CODE;
        if (typeCode == Types.SMALLINT) {
            // 自定义类型转换
            return DbColumnType.INTEGER;
        }
        return typeRegistry.getColumnType(metaInfo);

    }))
    .packageConfig(builder -> {
        builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
            .moduleName("system") // 设置父包模块名
            .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
    })
    .strategyConfig(builder -> {
        builder.addInclude("t_simple") // 设置需要生成的表名
            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
    })
    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
    .execute();

交互式生成

FastAutoGenerator.create(DATA_SOURCE_CONFIG)
    // 全局配置
    .globalConfig((scanner, builder) -> builder.author(scanner.apply("请输入作者名称?")).fileOverride())
    // 包配置
    .packageConfig((scanner, builder) -> builder.parent(scanner.apply("请输入包名?")))
    // 策略配置
    .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
                        .controllerBuilder().enableRestStyle().enableHyphenStyle()
                        .entityBuilder().enableLombok().addTableFills(
                                new Column("create_time", FieldFill.INSERT)
                        ).build())
    /*
        模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker
       .templateEngine(new BeetlTemplateEngine())
       .templateEngine(new FreemarkerTemplateEngine())
     */
    .execute();


// 处理 all 情况
protected static List<String> getTables(String tables) {
    return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}

完整的代码


import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.util.CollectionUtils;

import java.util.*;

public class CodeGenerator {

    public static void main(String[] args) {
        String password = "root";
        String username = "root";
        String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai";
        DataSourceConfig.Builder dataSourceConfig = new DataSourceConfig.Builder(url, username, password);

        String finalProjectPath = Objects.requireNonNull(CodeGenerator.class.getClassLoader().getResource(""))
                .getPath().replace("/target/classes/", "");

        List<String> tableList = new ArrayList<>();
        tableList.add("user"); // Add tables for code generation (use "all" to generate all tables)

        // Generate model classes
        createModel(dataSourceConfig, finalProjectPath, true, tableList);

        // Interactive mode for generating model classes
        createSingleModel(dataSourceConfig, finalProjectPath);
    }

    private static void createModel(DataSourceConfig.Builder dataSourceConfig,
                                    String finalProjectPath,
                                    boolean isOverride,
                                    List<String> tableList) {
        FastAutoGenerator.create(dataSourceConfig)
                .globalConfig(builder -> {
                    builder.author("shisan")
                            .fileOverride()
                            .disableOpenDir()
                            .outputDir(finalProjectPath + "/src/main/java");
                })
                .packageConfig(builder -> {
                    builder.parent("com.shisan")
                            .entity("model")
                            .controller("web.controller")
                            .mapper("dao")
                            .service("service")
                            .serviceImpl("service.impl")
                            .other("other")
                            .pathInfo(Collections.singletonMap(OutputFile.xml, finalProjectPath + "/src/main/resources/mapper"));
                })
                .strategyConfig(builder -> {
                    if (!CollectionUtils.isEmpty(tableList)) {
                        builder.addInclude(tableList);
                    }

                    builder.addTablePrefix("wms_");
                    builder.entityBuilder()
                            .enableRemoveIsPrefix()
                            .enableTableFieldAnnotation()
                            .enableLombok();

                    builder.controllerBuilder()
                            .enableRestStyle();

                    builder.serviceBuilder()
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            .fileOverride();

                    builder.mapperBuilder()
                            .enableBaseResultMap()
                            .enableMapperAnnotation()
                            .formatMapperFileName("%sDao")
                            .formatXmlFileName("%sMapper")
                            .enableBaseColumnList();

                    if (isOverride) {
                        builder.entityBuilder()
                                .fileOverride();
                        builder.controllerBuilder()
                                .fileOverride();
                        builder.serviceBuilder()
                                .fileOverride();
                        builder.mapperBuilder()
                                .fileOverride();
                    }
                })
                .injectionConfig(consumer -> {
                    Map<String, String> customFile = new HashMap<>();
                    consumer.customFile(customFile);
                })
                .templateEngine(new VelocityTemplateEngine())
                .execute();
    }

    private static void createSingleModel(DataSourceConfig.Builder dataSourceConfig, String finalProjectPath) {
        FastAutoGenerator.create(dataSourceConfig)
                .globalConfig((scanner, builder) ->
                        builder.author(scanner.apply("Please enter the author's name:"))
                                .fileOverride()
                                .outputDir(finalProjectPath + "/src/main/java"))
                .packageConfig(builder -> {
                    builder.parent("com.shisan")
                            .entity("model")
                            .other("dao")
                            .pathInfo(Collections.singletonMap(OutputFile.xml, finalProjectPath + "/src/main/resources/mapper"));
                })
                .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("Please enter table names (comma-separated), or type 'all' for all tables:")))
                        .controllerBuilder().enableRestStyle()
                        .entityBuilder().enableLombok()
                        .mapperBuilder().enableBaseResultMap().enableBaseColumnList()
                        .build())
                .execute();
    }

    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}

文章来源:https://blog.csdn.net/apple_51927114/article/details/135094237
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。