The use of mybatis plus code generator

Keywords: Java Mybatis MySQL Database

Code generator

MyBatis plus (MP for short) is an enhancement tool of MyBatis. Based on MyBatis, only enhancements are made and no changes are made to simplify development and improve efficiency.

Step demo

1, Add mybatis plus dependency

       <!--spring-boot web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--mysql rely on--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> <scope>runtime</scope> </dependency> <!--Generate entity into set set Method--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- mybatisPlus Core library --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency> <!-- Import Alibaba database connection pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <!-- mybatis plus Code generator --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.0.6</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency>

 

2, Create generator main class

package com.ckf.crm_generator.mapper;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 generator class
 *
 * @author Quiet Kuding tea
 * @version 1.0
 * @date 2020/3/23 15:53
 */
public class CodeGenerator {

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

    public static void main(String[] args) {
        // Code generator 
        AutoGenerator mpg = new AutoGenerator();

        // Global configuration
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("Quiet Kuding tea");
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        // Whether to open the output directory defaults to true
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);

        // Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/ckf_crm?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        // Package configuration
        final PackageConfig pc = new PackageConfig();
        // pc.setModuleName(scanner("Module name"));
        pc.setParent("com.ckf.crm_generator");
        mpg.setPackageInfo(pc);

        // Custom configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // If the template engine is freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // If the template engine is velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // Custom output configuration
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        // Custom configuration will be output first
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // Custom output filename if you Entity Pre suffix is set, note here xml The name of will change with it!!
                return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // Configure templates
        TemplateConfig templateConfig = new TemplateConfig();

        // Configure custom output templates
        // Specify the path of the custom template, be careful not to bring.ftl/.vm, Automatically recognized based on the template engine used
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

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

        // Policy configuration
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // strategy.setSuperEntityClass("com.fame.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // strategy.setSuperControllerClass("com.fame.common.BaseController");
        strategy.setInclude(scanner("Table name, multiple comma separated").split(","));
        strategy.setSuperEntityColumns("id");
        // strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("sys");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

 

This is the spring boot project

DSC. Seturl ("JDBC: MySQL: / / localhost: 3306 / CKF? CRM? Useunicode = true & usessl = false & characterencoding = utf8"); / / database url
gc.setOutputDir(projectPath + "/src/main/java"); / / set the file output path
Pc.setparent ("com. CKF. CRM? Generator"); / / parent package name


3, Then run the main method in the generator class, and enter the name of the database table in the console to generate three-tier code
The renderings are as follows

The following figure shows the path of my project (project structure after code generator execution):

 

Then it generates three layers of code in the style of mybatis plus
Entity class

 

 mapper

 

Next, I will not take screenshots of the code of those modules. If you are interested, you can try ha.

 

Note that before generating the code, make sure that the tables in the database already exist.

The project has been hosted in the code cloud
Address: https://gitee.com/ckfeng/crm_generator.git

Posted by luddeb on Sun, 03 May 2020 02:26:54 -0700