Spring Boot integrated MybatisPlus Implement universal code generation

HBLOG
4 min readMay 7, 2024

--

1.Background introduction

I believe many friends use it in their projects ORM Frames are all MyBatis, If used alone MyBatis If you want to operate a database, you need to write many single-table queries by hand. SQL accomplish.At this time we often choose an enhanced tool to implement these single tables CRUD Operation, here is a useful tool recommended MyBatis-Plus!

MyBatis-Plus( abbreviation MP) Is a MyBatis enhancement tools in MyBatis On the basis of only enhancements without changes, it was born to simplify development and improve efficiency. MyBatis-Plus Provides a code generator that can be generated with one click controller、service、mapper、model、mapper.xml code, while providing a rich CRUD How to operate to help us free our hands!

2.mysql Environmental 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 goals: Based on mysql Automatic generated crud code

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 resource Check the specific contents under the 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

Revise Generator Some generated parameters in the class, and then run main The method generates the corresponding code, the effect is as follows

Test whether the generated code is correct

start up Spring Boot Application, access address http://127.0.0.1:8088/userInfo/findAllUserInfo, The return result is 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}]

5.References

--

--

HBLOG
HBLOG

Written by HBLOG

talk is cheap ,show me your code

No responses yet