Spring Boot integrates MybatisPlus to achieve universal code generation

Estimated read time 7 min read

1. Background introduction

I believe that the ORM framework used by many friends in their projects is MyBatis. If you only use MyBatis to operate the database, you will need to hand-write many SQL implementations of single-table queries. At this time, we often choose an enhanced tool to implement these single-table CRUD operations. Here is a useful tool MyBatis-Plus recommended!

MyBatis-Plus (MP for short) is an enhancement tool for MyBatis. Based on MyBatis, it only enhances without making any changes. It is created to simplify development and improve efficiency. MyBatis-Plus provides a code generator that can generate controller, service, mapper, model, and mapper.xml codes with one click. It also provides a wealth of CRUD operation methods to help us free our hands!

2.mysql environment preparation

mysql setup

docker run --name docker-mysql-5.7 -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql:5.7

init data

create database demo;
create table user_info
(
user_id     varchar(64)          not null primary key,
username    varchar(100)         null ,
age         int(3)               null ,
gender      tinyint(1)           null ,
remark      varchar(255)         null ,
create_time datetime             null ,
create_id   varchar(64)          null ,
update_time datetime             null ,
update_id   varchar(64)          null ,
enabled     tinyint(1) default 1 null
);
INSERT INTO demo.user_info
(user_id, username, age, gender, remark, create_time, create_id, update_time, update_id, enabled)
VALUES('1', '1', 1, 1, '1', NULL, '1', NULL, NULL, 1);

remark

msyql username:root
mysql password:123456

3. Code engineering

Experimental goal: automatically generate crud code based on mysql

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>generator</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- spring boot -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
    </dependencies>
</project>

Tool generation class

package com.et.generator;

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;

public class Generator {
   
   public static void main(String[] args) {
      // System.getProperty("user.dir") == get current project dir
      String projectDir ="D:\\IdeaProjects\\ETFramework\\generator";
      String outputDir = projectDir+"\\src\\main\\java";
      //String outputDir = System.getProperty("user.dir") + "/src/main/java";
//    String outputDir = "C://Users/VULCAN/Desktop/new";
      // table name, Pay attention to capitalization
      String[] tableNames = new String[]{"user_info"};
      // database url
      String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8";
      String userName = "root";
      String password = "123456";
      // parentPackage
      String parentPackage = "com.et.generator";
      // need to remove prefix from tablename
      String prefixTable = "";
      generate(projectDir,outputDir, tableNames, url, userName, password, parentPackage, prefixTable);
   }
   
   /**
    * @param outputDir
    * @param tableNames
    * @param url
    * @param userName
    * @param password
    * @param parentPackage
    * @param prefixTable
    */
   public static void generate(String projectDir,String outputDir, String[] tableNames, String url, String userName,
         String password, String parentPackage, String prefixTable) {
      // ===============  Global setting ==================
      GlobalConfig gc = new GlobalConfig();
      gc.setOutputDir(outputDir)
         .setActiveRecord(true)                      //  enable AR,
           .setAuthor("Harries")                    // set Author name
           .setFileOverride(true)                          // enable FileOverride?
           .setIdType(IdType.AUTO)                         //primary strategy
           .setBaseResultMap(true)                      // SQL mappingg
           .setBaseColumnList(true)                     // SQL BaseColumn
           .setServiceName("%sService")                  // service name
           .setOpen(false);
      
      // =================  database setting   ===============
      DataSourceConfig dsc = new DataSourceConfig();
         dsc.setDbType(DbType.MYSQL)
          .setDriverName("com.mysql.cj.jdbc.Driver");
      dsc.setUrl(url)
           .setUsername(userName)
           .setPassword(password);
      
      // =================  package setting  ===================
       PackageConfig pc = new PackageConfig();
         pc.setParent(parentPackage)                     // parentPackage path
//           .setModuleName("base")                         // ModuleName path
           .setMapper("mapper")
           .setEntity("entity")
//           .setEntity("entity")
           .setService("service")
           //.setServiceImpl("service.impl");              // auto generate impl, no need to set
           .setController("controller");
         
       // ==================  custom setting  =================
         InjectionConfig cfg = new InjectionConfig() {
             @Override
             public void initMap() {
                 // to do nothing
             }
         };
         List<FileOutConfig> focList = new ArrayList<>();
         // adjust xml generate directory
         focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
             @Override
             public String outputFile(TableInfo tableInfo) {
                 // custom file name
                 return projectDir + "/src/main/resources/mybatis/"
                         + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
             }
         });
         cfg.setFileOutConfigList(focList);
         
         // ===================  strategy setting  ==================
         StrategyConfig strategy = new StrategyConfig();
         strategy.setNaming(NamingStrategy.underline_to_camel)             // table name:  underline_to_camel
                 .setColumnNaming(NamingStrategy.underline_to_camel)         // file name: underline_to_camel
                 .setInclude(tableNames)                              // tableNames
                 .setCapitalMode(true)                               // enable CapitalMod(ORACLE )
                 .setTablePrefix(prefixTable)                          // remove table prefix
//                 .setFieldPrefix(pc.getModuleName() + "_")               // remove fields prefix
//                 .setSuperEntityClass("com.maoxs.pojo")                 // Entity implement
//                 .setSuperControllerClass("com.maoxs.controller")             // Controller implement
//                 .setSuperEntityColumns("id")                         // Super Columns
//                 .setEntityLombokModel(true)                         // enable lombok
                 .setControllerMappingHyphenStyle(true);                  // controller MappingHyphenStyle
       
         // ==================  custome template setting:default mybatis-plus/src/main/resources/templates  ======================
         //default: src/main/resources/templates directory
         TemplateConfig tc = new TemplateConfig();
         tc.setXml(null)                                            // xml template
           .setEntity("/templates/entity.java")                           // entity template
           .setMapper("/templates/mapper.java")                           // mapper template
           .setController("/templates/controller.java")                 // service template
           .setService("/templates/service.java")                    // serviceImpl template
           .setServiceImpl("/templates/serviceImpl.java");             // controller template
         
         // ====================  gen setting  ===================
         AutoGenerator mpg = new AutoGenerator();
         mpg.setCfg(cfg)
                 .setTemplate(tc)
                 .setGlobalConfig(gc)
                 .setDataSource(dsc)
                 .setPackageInfo(pc)
                 .setStrategy(strategy)
                 .setTemplateEngine(new FreemarkerTemplateEngine());          // choose freemarker engine,pay attention to pom dependency!
         mpg.execute();
   }

}

template file

There are too many template files, so I won’t post them here. You can view the specific contents in the resource folder.

DemoApplication

package com.et.generator;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.et.generator.mapper")
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

}

application.yaml

server:
  port: 8088

spring:
  datasource:
    password: 123456
    username: root
    url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath*:/mybatis/*.xml

The above are just some key codes. For all codes, please see the code repository below.

code repository

4. Test

generate

Modify some generation parameters in the Generator class, and then run the main method to generate the corresponding code. The effect is as follows 

Test whether the generated code is correct

Start the Spring Boot application and access the address http://127.0.0.1:8088/userInfo/findAllUserInfo. The returned results are as follows:

[{"userId":"1","username":"1","age":1,"gender":true,"remark":"1","createTime":null,"createId":"1","updateTime":null,"updateId":null,"enabled":true},{"userId":"2","username":"2","age":2,"gender":true,"remark":"2","createTime":null,"createId":"2","updateTime":null,"updateId":null,"enabled":true}]

You May Also Like

More From Author

+ There are no comments

Add yours