Want to be a master of time management? You can try the Mybatis Plus code generator

1. Preface

For the old driver who writes Crud, time is very precious. Some sample code writing is not only time-consuming and laborious, but also boring. My little friend often asks me why you have so much time to make new things every day. Let me tell you the secret.

Well, today, I will share the code generator of mybatis plus to make you an excellent time management master.

2. basic dependency

Take Spring Boot and MySQL for example. You need the following dependencies:

<!-- lombok If you do not use, you need to modify the relevant configuration of the code generator -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>compile</scope>
</dependency>
<!-- You can replace the connection pool with another one -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
</dependency>
<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis plus starter -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- mybatis plus Generator module -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <scope>compile</scope>
    <optional>true</optional>
</dependency>
<!-- lead into freemarker Package as code generator engine -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <scope>compile</scope>
    <optional>true</optional>
</dependency>

Then configure your database to ensure smooth database connection and communication.

3. custom code generator

Here, I expect the generated directory structure to be as follows:

So I spent some time customizing the configuration of some generators. The code is as follows. This is the hard core!

package cn.felord.mybatis.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.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.Optional;


/**
 * Code generator configuration
 *
 * @author felord
 * @since 10 :39  2018/9/9
 */
public class CodeGenerator {
    private String dbUrl;
    private String userName;
    private String password;
    private String dir;
    private String xmlDir;
    private String packageName;

    private CodeGenerator() {
    }

    /**
     * The type Config builder.
     */
    public static class ConfigBuilder {

        private String dbUrl;
        private String userName;
        private String password;
        private String dir;
        private String xmlDir;
        private String packageName;


        /**
         * Db url config builder.
         *
         * @param dbUrl the db url
         * @return the config builder
         */
        public ConfigBuilder dbUrl(final String dbUrl) {
            this.dbUrl = dbUrl;
            return this;
        }

        /**
         * User name config builder.
         *
         * @param userName the user name
         * @return the config builder
         */
        public ConfigBuilder userName(final String userName) {
            this.userName = userName;
            return this;
        }

        /**
         * Password config builder.
         *
         * @param password the password
         * @return the config builder
         */
        public ConfigBuilder password(final String password) {
            this.password = password;
            return this;
        }

        /**
         * Dir config builder.
         *
         * @param dir the dir
         * @return the config builder
         */
        public ConfigBuilder dir(final String dir) {
            this.dir = dir;
            return this;
        }

        /**
         * Dir config builder.
         *
         * @param xmlDir the dir
         * @return the config builder
         */
        public ConfigBuilder xmlDir(final String xmlDir) {
            this.xmlDir = xmlDir;
            return this;
        }

        /**
         * Package name config builder.
         *
         * @param packageName the package name
         * @return the config builder
         */
        public ConfigBuilder packageName(final String packageName) {
            this.packageName = packageName;
            return this;
        }

        /**
         * Build code generator.
         *
         * @return the code generator
         */
        public CodeGenerator build() {
            CodeGenerator generator = new CodeGenerator();

            generator.dbUrl = Optional.of(this.dbUrl).get();
            generator.userName = Optional.of(this.userName).get();
            generator.password = Optional.of(this.password).get();
            generator.dir = Optional.of(this.dir).get();
            generator.xmlDir = Optional.of(this.xmlDir).get();
            generator.packageName = Optional.of(this.packageName).get();
            return generator;
        }
    }


    /**
     * Code.
     *
     * @param tableNames the table names
     */
    public void code(String... tableNames) {
        codingMysql(true, false, true, this.dbUrl, this.userName, this.password, this.dir, this.xmlDir, this.packageName, tableNames);
    }

    /**
     *
     * Generator core
     *
     * @param serviceNameStartWithI Prefix I or not
     * @param createController      Generate controller
     * @param useLombok             Use lombok
     * @param dbUrl                 Database connection
     * @param username              User name
     * @param password              password
     * @param outDir                Output directory
     * @param xmlDir                xml File directory
     * @param packageName           Package path
     * @param tableNames            Table name
     */
    private static void codingMysql(boolean serviceNameStartWithI,
                                    boolean createController,
                                    boolean useLombok,
                                    String dbUrl,
                                    String username,
                                    String password,
                                    String outDir,
                                    String xmlDir,
                                    String packageName,
                                    String... tableNames) {
        GlobalConfig config = new GlobalConfig();
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
//        Database type mysql is used here
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername(username)
                .setPassword(password)
//                Driver name: mysql is used here
                .setDriverName("com.mysql.jdbc.Driver");

        // Custom xml output path
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
//        You can also customize xml templates
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // Path to custom xml file
                return xmlDir + "/mapper/" + tableInfo.getMapperName() + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);


//        Policy configuration item
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(false)
//                Use lombok
                .setEntityLombokModel(useLombok)
//                Underline to hump
                .setNaming(NamingStrategy.underline_to_camel)
                //Modify and replace with the table name you need. Multiple table names are passed to the array
                .setInclude(tableNames);
//        Use AR mode
        config.setActiveRecord(true)
//                Set the author of the header annotation
                .setAuthor("system")
//                Project output path
                .setOutputDir(outDir)
//                Overwrite the generated file with the same name
                .setFileOverride(true)
//                Snowflake algorithm generation id
                .setIdType(IdType.ASSIGN_ID)
//                Whether to use cache
                .setEnableCache(false)
//                Generate basic resultMap in xml
                .setBaseResultMap(true);
        if (!serviceNameStartWithI) {
//            Common format suffix of Service layer
            config.setServiceName("%sService");
        }
//             Entity class package name
        PackageConfig packageConfig = new PackageConfig().setParent(packageName).setEntity("entity");
        TemplateConfig templateConfig = new TemplateConfig().setXml(null);
//        Choose not to generate the controller here. In fact, most of the generated controllers do not meet the requirements of the service layer
        if (!createController) {
            templateConfig.setController(null);
        }
//        Integrated operation
        new AutoGenerator()
                .setGlobalConfig(config)
                .setTemplateEngine(new FreemarkerTemplateEngine())
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setCfg(cfg)
                .setTemplate(templateConfig)
                .execute();
    }

}

If the directory structure I generated can meet your needs, it's a coincidence. Take it directly; If it doesn't meet your needs, you can fine tune it according to the notes. It took several years to do it in 18 years without any trouble.

4. use of code generator

It is very easy to use. Make sure that the database can be successfully connected using JDBC. Write a main method, configure it, and run it:

/**
 * @author felord.cn
 * @since 11:34
 **/
public class AutoCoding {
    public static void main(String[] args) {

//          Full path of maven project main package
        final String mainDir = "C:\\IdeaProjects\\bc-recyling\\src\\main\\";

        CodeGenerator.ConfigBuilder builder = new CodeGenerator.ConfigBuilder();

        CodeGenerator codeGenerator = builder
//                Database connection
                .dbUrl("jdbc:mysql://localhost:3306/test")
//                account
                .userName("root")
//                password
                .password("123456")
                // Build class location
                .dir(mainDir + "java")
                // Generate xml location
                .xmlDir(mainDir + "resources")
                // Package reference path
                .packageName("cn.felord.mybatis")
                .build();

        //Generate background code based on table
        codeGenerator.code("user_info");


    }
}

Then the code is generated. Is it very easy to use? Congratulations on getting the honorary title of time management master.

Remember not to show off, or the demand will double.

5. summary

Although it is easy to use, it is recommended that novices do not use it and write more code. In addition, it is recommended to write complex SQL by yourself and exercise your ability to write SQL. If you have any problems in use, you can communicate with me by private letter.

Follow official account: Felordcn for more information

Personal blog: https://felord.cn

Posted by BryonS on Thu, 02 Jun 2022 08:54:24 +0530