Mybatis plus learning notes: code generator

AutoGenerator is the code generator of mybatis plus. Through AutoGenerator, you can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules.

Project structure:

Before generation:

After generation:

pom.xml:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.29</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>

Code generation main class: PlusGenerator

package com.cf.plusdm2;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

public class PlusGenerator {

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

        //Global configuration
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        //Output directory of the build file
        gc.setOutputDir(projectPath + "/src/main/java");
        //Developer
        gc.setAuthor("bure");
        //Open output directory or not
        gc.setOpen(false);
        //Whether to overwrite the existing file, false by default
        gc.setFileOverride(true);
        //Entity attribute Swagger2 annotation
        //gc.setSwagger2(true);
        //Generating general query result columns in mapper.xml
        gc.setBaseColumnList(true);
        //Generate general query mapping results in mapper.xml
        gc.setBaseResultMap(true);
        //Set the naming methods such as Controller, Mapper, mapper.xml, and use the default.
        /*gc.setServiceName("%sService");
        gc.setControllerName();
        gc.setMapperName();
        gc.setEntityName();
        gc.setXmlName();
        gc.setServiceImplName();*/
        mpg.setGlobalConfig(gc);


        //Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost/localdb?useUnicode=true&characterEncoding=UTF-8");
        //Database schema name
        // dsc.setSchemaName("public");
        //Database driven
        dsc.setDriverName("com.mysql.jdbc.Driver");
        //Database connection user name
        dsc.setUsername("root");
        //Database connection password
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);


        //Packet configuration
        PackageConfig pc = new PackageConfig();
        //Parent package module name
        pc.setModuleName("user");
        //The name of the parent package. If it is empty, the name of the child package must be written in all, otherwise only the name of the child package needs to be written
        pc.setParent("com.cf.plusdm2");
        //Set the package name stored in Controller, Mapper, mapper.xml, etc
        /*pc.setController();
        pc.setEntity();
        ...*/
        mpg.setPackageInfo(pc);


        // Policy configuration
        StrategyConfig strategy = new StrategyConfig();
        //Naming strategy of database table mapping to entity
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //Naming policy of database table fields mapped to entities, not specified to be executed according to naming
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //Whether it is a lombok model, false by default
        strategy.setEntityLombokModel(true);
        //Generate @ RestController controller controller
        strategy.setRestControllerStyle(true);
        //Table name to include, regular expression allowed
        strategy.setInclude("tb_user");
        //Camel to hyphen
        strategy.setControllerMappingHyphenStyle(true);
        //Table prefix
        strategy.setTablePrefix("tb_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

When the above generation cannot meet the requirements, mybatis plus also provides methods for custom generation, such as using InjectionConfig and TemplateConfig.

Custom build Controller

1. First, create the FreeMarker template file used to generate the Controller. The content can be modified by referring to the template file of com.baomidou.mybatis-plus-generator.3.3.1.tmp.mybatis-plus-generator-3.3.1.tmp.jar!. templates.Controller.java.ftl (the template file of the default Controller).
src/main/resources/ftl/controller.java.ftl:

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
<#if cfg.servicePackage??>
import ${cfg.servicePackage}.${table.serviceName};
</#if>
<#if cfg.entityPackage??>
import ${cfg.entityPackage}.${table.entityName};
</#if>

/**
 * <p>
 * ${table.comment!} Front end controller
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
     @Autowired
     private ${table.serviceName} ${table.serviceName?uncap_first};

     @RequestMapping("/add")
     public String insert(User user){
         return ${table.serviceName?uncap_first}.save(user) ? "success" : "fail";
     }
}
</#if>

2. Add the configuration of InjectionConfig and TemplateConfig above the policy configuration in PlusGenerator:

        //Custom configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        //The parameters passed in to the template are obtained through cfg.servicePackage in the template
        Map<String, Object> map = new HashMap<>();
        map.put("servicePackage", pc.getParent() + "." + pc.getService());
        map.put("entityPackage", pc.getParent() + "." + pc.getEntity());
        cfg.setMap(map);
        mpg.setCfg(cfg);

        //Configuration template
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setController("/ftl/controller.java");
        mpg.setTemplate(templateConfig);

Use the templateConfig.setController() method to set the template to generate the controller. Be careful not to bring. ftl/.vm, which will be automatically recognized according to the template engine used. When no value is set, the default template provided by the default mybatis plus is used. When set to null, the controller is not generated. (mapper, service, etc.)

Run PlusGenerator again. The generated Controller is as follows:

package com.cf.plusdm2.user.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import com.cf.plusdm2.user.service.IUserService;
import com.cf.plusdm2.user.entity.User;

/**
 * <p>
 *  Front end controller
 * </p>
 *
 * @author bure
 * @since 2020-02-10
 */
@RestController
@RequestMapping("/user/user")
public class UserController {
     @Autowired
     private IUserService iUserService;

     @RequestMapping("/add")
     public String insert(User user){
         return iUserService.save(user) ? "success" : "fail";
     }
}

For detailed use of code generator, please refer to: Code generator

Tags: Java Mybatis xml Database

Posted on Mon, 10 Feb 2020 07:49:40 -0800 by Mahfouz