1. Introduction

Time is precious for Crud veterans, and boilerplate code is time-consuming and tedious. My friends often ask me, fat brother, how do you have time to do new things every day, reveal the secret.

Well, share Mybatis- Plus code generator today to make you a good time management guru, too.

2. Basic dependencies

In the case of Spring Boot and MySQL, you need the following dependencies:

<! -- Lombok does not need to modify the configuration of the code generator if it is not used.
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>compile</scope>
</dependency>
<! You can replace the connection pool with something else -->
<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>
<! -- Introduce 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>
Copy the code

Then configure your database to ensure that the database connection communication is smooth.

3. Custom code generators

Here I expect the generated directory structure to look like this:

So I spent some time customizing the configuration of the generator, and the code is as hardcore as it is!

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(a) {}/** * 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(a) {
            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();
            returngenerator; }}/**
     * 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);
    }

    /** ** Core part of generator **@paramServiceNameStartWithI Specifies whether the prefix is I *@paramCreateController Whether to generate controller *@paramWhether useLombok uses Lombok *@paramDbUrl database connection *@paramUsername username *@param"Password," password *@paramOutDir Output directory *@paramXmlDir XML file directory *@paramPackageName Indicates the package path *@paramTableNames 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();
// The database type is mysql
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername(username)
                .setPassword(password)
// The driver name is mysql
                .setDriverName("com.mysql.jdbc.Driver");

        // Customize the XML output path
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap(a) {
                // to do nothing}}; List<FileOutConfig> focList =new ArrayList<>();
// You can also customize the XML template
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // Customize the path of the XML file
                return xmlDir + "/mapper/"+ tableInfo.getMapperName() + StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList);// Policy configuration item
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(false)
// Whether to use Lombok
                .setEntityLombokModel(useLombok)
// Underline the hump
                .setNaming(NamingStrategy.underline_to_camel)
                // Change the table name to the one you need
                .setInclude(tableNames);
// Use AR mode
        config.setActiveRecord(true)
// Set the author of the header comment
                .setAuthor("system")
// Project output path
                .setOutputDir(outDir)
// Whether to overwrite an already generated file with the same name
                .setFileOverride(true)
// The snowflake algorithm generates the ID
                .setIdType(IdType.ASSIGN_ID)
// Whether to use cache
                .setEnableCache(false)
// Whether to generate the base resultMap in XML
                .setBaseResultMap(true);
        if(! serviceNameStartWithI) {// Common format suffix for the 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 controller. In fact, most of the generated controller does not meet our need to go to the service layer
        if(! createController) { templateConfig.setController(null);
        }
// run it together
        new AutoGenerator()
                .setGlobalConfig(config)
                .setTemplateEngine(new FreemarkerTemplateEngine())
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setCfg(cfg)
                .setTemplate(templateConfig)
                .execute();
    }

}

Copy the code

If I’ve generated a directory structure that meets your needs, then it’s a coincidence, just use it. If not, you can follow the instructions in the comments to make fine tuning. 18 years, took a couple of years, and nothing went wrong.

4. Use of code generators

To make sure the database can successfully connect using JDBC, write a main method, configure it, and run it:

/ * * *@author felord.cn
 * @sinceThe name * * /
public class AutoCoding {
    public static void main(String[] args) {

// The full path of the 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")
                // Generate the class location
                .dir(mainDir + "java")
                // Generate the XML location
                .xmlDir(mainDir + "resources")
                // Package reference path
                .packageName("cn.felord.mybatis")
                .build();

        // Generate background code according to the table
        codeGenerator.code("user_info"); }}Copy the code

And then the code is generated, doesn’t it work pretty well? Congratulations on being honored as a Time Management Master.

Remember not to show off, or demand will double.

5. To summarize

Although easy to use, but suggest novice do not use, more handwritten code. In addition to the complex SQL or suggest to write their own, more exercise to write SQL ability. If you have any problems in use, you can send me a private message to communicate.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn