Code generation tools for mybatis-plus3.5.x and 3.4.x versions

Foreword

In the past two days, I have been working on upgrading the open source components of the projects I am in charge of, because many components have loopholes, and the version needs to be upgraded. Then mybatis-plus is also one of them, because the version I have been using is 3.4.3, and now I have to upgrade to version 3.5.2 or above. However, some changes in 3.4.x and 3.5.x are still quite large, mainly in the area of code generation. The changes are relatively large, and the generation tools written before can no longer be used. Then now rewrite the 3.5.x generation tool class.

Here I put both 3.4 and 3.5, you can compare and refer to it.

Version 3.4.x

<!-- mybatis_plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>
<!-- code generator -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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;

/**
 * Code generation tool class
 */
public class GenerateUtil {<!-- -->
    /**
     * Database link address
     */
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true &characterEncoding=utf8 &allowMultiQueries=true &useSSL=false &serverTimezone=UTC";

    /**
     * drive
     */
    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

    /**
     * username
     */
    private static final String USERNAME = "root";

    /**
     * password
     */
    private static final String PASSWORD = "123456";

    /**
     * author
     */
    private static final String AUTHOR = "fuHua";

    /**
     * parent package name
     */
    private static final String PACKAGE_PARENT = "com";

    public static String scanner(String tip) {<!-- -->
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("Please input" + tip + ":");
        System.out.println(help.toString());
        if (scanner. hasNext()) {<!-- -->
            String ipt = scanner. next();
            if (StrUtil.isNotEmpty(ipt)) {<!-- -->
                return ipt;
            }
        }
        throw new MybatisPlusException("Please enter the correct " + tip + "!");
    }

    /**
     * Global configuration
     *
     * @return return GlobalConfig
     */
    private static GlobalConfig getGlobalConfig() {<!-- -->
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System. getProperty("user. dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(AUTHOR);
        gc.setOpen(false);
        // Whether to overwrite the file with the same name, the default is false
        gc.setFileOverride(true);
        // If you don't need the ActiveRecord feature, please change it to false
        gc.setActiveRecord(false);
        // XML second level cache
        gc.setEnableCache(false);
        // XML ResultMap generates a basic resultmap
        gc.setBaseResultMap(true);
        // XML columList generates basic sql fragments
        gc.setBaseColumnList(false);
        //Entity attribute Swagger2 annotation
        //gc.setSwagger2(true);
        gc.setServiceName("");
        gc.setServiceImplName("%sService");
        return gc;
    }

    /**
     * Data source configuration
     *
     * @return return getDataSourceConfig
     */
    private static DataSourceConfig getDataSourceConfig() {<!-- -->
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        return dsc;
    }

    /**
     * Package name configuration
     *
     * @return return PackageConfig
     */
    private static PackageConfig getPackageConfig() {<!-- -->
        PackageConfig pc = new PackageConfig();
        pc.setParent(PACKAGE_PARENT);
        //pc.setModuleName(scanner("module name"));
        pc.setEntity("entity.sys");
        pc.setMapper("mapper.sys");
        pc.setService("");
        pc.setServiceImpl("service.sys");
        pc.setController("controller.sys");
        return pc;
    }

    /**
     * Template engine configuration
     *
     * @return return TemplateConfig
     */
    private static TemplateConfig getTemplateConfig() {<!-- -->
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        return templateConfig;
    }

    /**
     * Policy configuration
     *
     * @param tableNames table name
     * strategy.setInclude(tableNames) Pass in the table names that need to be "generated"
     * strategy.setExclude(tableNames) pass in the table names that need to be "filtered"
     * strategy.setSuperEntityColumns("id");
     * @return return getStrategyConfig
     */
    private static StrategyConfig getStrategyConfig(String... tableNames) {<!-- -->
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        // public parent class
        strategy.setSuperEntityClass(PACKAGE_PARENT + ".common.base.BaseEntity");
        strategy.setSuperMapperClass(strategy.getSuperMapperClass());
        strategy.setSuperServiceImplClass(PACKAGE_PARENT + ".common.base.BaseService");
        strategy.setSuperControllerClass(PACKAGE_PARENT + ".common.base.BaseController");

        // Write to the public field in the parent class
        strategy.setSuperEntityColumns("id", "create_by", "create_time", "update_by", "update_time");

        strategy.setInclude(tableNames);
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("_");
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setEntityLombokModel(true);
        return strategy;
    }

    /**
     * Custom configuration
     *
     * @return return InjectionConfig
     */
    private static InjectionConfig getInjectionConfig() {<!-- -->
        // custom configuration
        InjectionConfig cfg = new InjectionConfig() {<!-- -->
            @Override
            public void initMap() {<!-- -->
                // to do nothing
            }
        };
        // If the template engine is freemarker
        final String templatePath = "/templates/mapper.xml.ftl";
        // custom output configuration
        List<FileOutConfig> focList = new ArrayList<>();
        // Custom configuration will be output first
        focList.add(new FileOutConfig(templatePath) {<!-- -->
            @Override
            public String outputFile(TableInfo tableInfo) {<!-- -->
                // Customize the output file name, if you set the prefix and suffix for Entity, note here that the name of xml will change accordingly! !
                return System.getProperty("user.dir") + "/src/main/resources/mapper/sys/" + tableInfo.getEntityName() + "Mapper" + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    public static void main(String[] args) {<!-- -->
        // Code generator
        AutoGenerator mpg = new AutoGenerator();
        // global configuration
        mpg.setGlobalConfig(getGlobalConfig());
        // data source configuration
        mpg.setDataSource(getDataSourceConfig());
        // package configuration
        mpg.setPackageInfo(getPackageConfig());
        // custom configuration
        mpg.setCfg(getInjectionConfig());
        // configuration template
        mpg.setTemplate(getTemplateConfig());
        // policy configuration
        //sys_dept, sys_dict, sys_log, sys_menu, sys_post, sys_role, sys_role_dept, sys_role_menu, sys_user, sys_user_post
        mpg.setStrategy(getStrategyConfig(scanner("table name, separated by multiple English commas").split(",")));
        // set template engine
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg. execute();
    }
}

Version 3.5.x

<!-- mybatis_plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.1</version>
</dependency>
<!-- code generator -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.3.1</version>
</dependency>
<!-- The template engine for the code generator -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

Note: The template engine of the code generator must be introduced, otherwise an error will be reported when running: org/apache/velocity/context/Context

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.common.base.BaseController;
import com.common.base.BaseEntity;
import com.common.base.BaseService;

import java.util.Collections;
import java.util.List;

/**
 * Code generation tool class
 */
public class CodeGenerator {<!-- -->

    /**
     * Database link address
     */
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true &characterEncoding=utf8 &allowMultiQueries=true &useSSL=false &serverTimezone=UTC";

    /**
     * username
     */
    private static final String USERNAME = "root";

    /**
     * password
     */
    private static final String PASSWORD = "123456";

    /**
     * author
     */
    private static final String AUTHOR = "fuHua";

    /**
     * The prefix of the table name, the prefix will be removed when generating code from the table
     */
    private static final String TABLE_PREFIX = "";

    /**
     * module name
     */
    //private static final String MODULE_NAME = "";

    /**
     * The name of the table to be generated, required
     */
    private static final List<String> TABLES = ListUtil.toList("aqhdjl","aqyh","bqbhhjl","bwhyjl","chzttd","czpcx","dzhyj","gqjjc","gzpcx"," qxdcx","whjx","yxfsd","zhtd");


    public static void main(String[] args) {<!-- -->
        if (CollUtil.isEmpty(TABLES)) {<!-- -->
            System.out.println("Please enter the name of the table to be generated!");
            return;
        }

        String projectPath = System. getProperty("user. dir");

        //global configuration
        GlobalConfig config = new GlobalConfig. Builder()
                .author(AUTHOR) //Author
                .outputDir(projectPath + "/src/main/java") //generate file output path (write to java directory)
                //.enableSwagger() //Enable swagger
                .commentDate("yyyy-MM-dd HH:mm:ss") //comment date format
                .fileOverride() //overwrite file (use with caution)
                .dateType(DateType.TIME_PACK) //Set the corresponding type of time
                .disableOpenDir() //Do not open the directory after generation
                .build();

        //package name configuration
        PackageConfig packageConfig = new PackageConfig.Builder()
                .parent("com") //parent package name
                //.moduleName(moduleName) //module name
                .controller("controller.sys") //controller package name
                //.service("service.sys") //service interface package name
                .serviceImpl("service.sys") //service implementation class package name
                .entity("entity.sys") //Entity class package name
                .mapper("mapper.sys") //mapper package name
                .xml("mapper.sys") //The xml package name corresponding to mapper
                .pathInfo(Collections.singletonMap(OutputFile.mapper.xml, projectPath + "/src/main/resources/mapper/sys")) //the xml path corresponding to the mapper
                .build();

        //Strategy configuration
        StrategyConfig strategyConfig = new StrategyConfig. Builder()
                .addTablePrefix(TABLE_PREFIX) //The table prefix that needs to be offset
                .addInclude(TABLES) //Set the name of the table that needs to be mapped
                //.enableCapitalMode() //Strategy enabled? Write name
                .serviceBuilder() //Build the Service layer
                .formatServiceImplFileName("%sService") //Business layer interface implementation class naming
                .superServiceImplClass(BaseService.class) //service public parent class
                .entityBuilder() //Build entity class
                .superClass(BaseEntity.class) //entity public parent class
                .addSuperEntityColumns("id","updateTime","createTime") // public field
                .columnNaming(NamingStrategy.underline_to_camel) //field name camel case naming
                .naming(NamingStrategy.underline_to_camel) //Table name camel case naming
                .enableLombok() //Add getter and setter annotations for lombock
                //.enableChainModel() //Start chain writing @Accessors(chain = true)
                //.enableColumnConstant() //Start property conversion function @FieldNameConstants
                //.logicDeleteColumnName("deleted") //Logic delete field, marked @TableLogic
                .enableTableFieldAnnotation() //Enable field annotation
                //.addTableFills(tableFillList) //Attribute value filling strategy
                .controllerBuilder() //Build Controller class
                .enableHyphenStyle() //The mapping path uses hyphen format instead of camel case
                .formatFileName("%sController") //Controller class naming
                .superClass(BaseController.class) //Controller class inherits from BaseController
                .enableRestStyle() //mark @RestController annotation
                .mapperBuilder() //Build mapper interface class
                .enableBaseResultMap() // Generate a basic resultMap
                .formatMapperFileName("%sMapper") //Mapper interface class name
                .superClass(BaseMapper.class) //Mapper interface class integrates BaseMapper
                //.enableMapperAnnotation() //Mark @Mapper annotation
                .formatXmlFileName("%sMapper") //Mapper.xml naming
                .enableBaseColumnList() // Generate basic SQL fragments
                .build();

        //data source configuration
        DataSourceConfig.Builder dataSourceConfigBuilder = new DataSourceConfig.Builder(URL,USERNAME,PASSWORD);
        //Database type converter
        dataSourceConfigBuilder.typeConvert(new MySqlTypeConvert() {<!-- -->
            /* @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String tableField) {
                if (tableField.toLowerCase().contains("date") || tableField.toLowerCase().contains("timestamp") || tableField.toLowerCase().contains("datetime")) {
                    return DbColumnType. STRING;
                }
                return super.processTypeConvert(globalConfig, tableField);
            }*/
        });

        //Create a code generator object and load the configuration
        AutoGenerator autoGenerator = new AutoGenerator(dataSourceConfigBuilder. build());
        autoGenerator.global(config);
        autoGenerator. packageInfo(packageConfig);
        autoGenerator. strategy(strategyConfig);

        //implement
        autoGenerator. execute();
        System.out.println("=========================================== Related code generation Done =======================================");
    }
}

The above is all the code. After the dependency is introduced, the code can be copied and used directly. Change the database connection, user name, password, and package name.