MybatisPlus代码生成器

前序


​一文带你了解MybatisPlus基本使用​

​ ​ ​​ ​Spring、SpringBoot整合Mybatis-Plus详细教程​

​​ ​MybatisPlus通⽤ CRUD接口​

​ ​ ​​ ​MybatisPlus之条件构造器​

​​ ​MybatisPlus中代码生成器教程详解​

​​ ​MybatisPlus之配置​


前言

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。因此本 文章 介绍如何使用 MyBatis-Plus的代码生成器如何使用。

基于Spring整合Mybatis-Plus代码生成器

创建Spring项目并导入依赖

<dependencies>
<!--mp核心依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>

在test文件下创建CodeGeneratorTest文件

public class CodeGeneratorTest {
/**
* <p>
* 读取控制台内容
* </p>
*/
@Test
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}

public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
//获取当前系统目录
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("author"); //生成作者注释
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(false);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
//数据库类型
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);

// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("test"); //模块名,可以不设置
//放在哪个包下,父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
pc.setParent("com.mybatis");
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 自定义包配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};

// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";

// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});

cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
//数据库表映射到实体的命名策略
strategy.setNaming(NamingStrategy.underline_to_camel);
//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//自定义继承的Entity类全称,带包名
strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
//是否为lombok模型(默认 false)
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
// 公共父类
strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}

打开目录就可以看到生成的文件

MybatisPlus中代码生成器教程详解_后端

MybatisPlus中代码生成器教程详解_MyBatis_02

基于SpringBoot整合Mybatis-Plus代码生成器

创建SpringBoot项目

MybatisPlus中代码生成器教程详解_包名_03

引入依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lagou</groupId>
<artifactId>springBoot-mp-generator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mp-generator</name>
<description>Demo project for Spring Boot</description>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!--mybatis-plus的springboot支持-->
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

在test文件下创建CodeGeneratorTest文件

public class CodeGenerator {

/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}

/**
* RUN THIS
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();

// 全局配置
GlobalConfig gc = new GlobalConfig();
final String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("author");
gc.setOpen(false);
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);

// 包配置
final PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.mybatis.mp.generator");
mpg.setPackageInfo(pc);

// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));

// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity");
strategy.setEntityLombokModel(true);
// strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController");
strategy.setInclude(scanner("表名"));
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}

测试并验证

MybatisPlus中代码生成器教程详解_后端

MybatisPlus中代码生成器教程详解_MyBatis_02

代码生成器常用配置

数据源 dataSourceConfig 配置

  • dbQuery

数据库 信息查询类 默认由 dbType 类型决定选择对应数据库内置实现 实现 IDbQuery 接口自定义数据库查询 SQL 语句 定制化返回自己需要的内容

  • dbType

数据库 类型 该类内置了常用的数据库类型【必须】

  • schemaName

数据库 schema name 例如 PostgreSQL 可指定为 public

  • typeConvert

类型转换 默认由 dbType 类型决定选择对应 数据库 内置实现 实现 ITypeConvert 接口自定义数据库 字段类型 转换为自己需要的 java 类型,内置转换类型无法满足可实现 IColumnType 接口自定义

  • url

驱动连接的URL

  • driverName

驱动名称

  • username

数据库 连接用户名

  • password

数据库 连接密码

数据库表配置

  • isCapitalMode

是否大写命名

  • skipView

是否跳过视图

  • naming

数据库 表映射到实体的命名策略

  • columnNaming

数据库 表字段映射到实体的命名策略, 未指定按照 naming 执行

  • tablePrefix

表前缀

  • fieldPrefix

字段前缀

  • superEntityClass

自定义继承的Entity类全称,带包名

  • superEntityColumns

自定义基础的Entity类,公共字段

  • superMapperClass

自定义继承的Mapper类全称,带包名

  • superServiceClass

自定义继承的Service类全称,带包名

  • superServiceImplClass

自定义继承的ServiceImpl类全称,带包名

  • superControllerClass

自定义继承的Controller类全称,带包名

  • enableSqlFilter(since 3.3.1)

默认激活进行sql模糊表名匹配关闭之后likeTable与notLikeTable将失效,include和exclude将使用内存过滤 如果有sql语法兼容性问题的话,请手动设置为false 已知无法使用:MyCat中间件, 支持情况传送门(opens new window)

  • include

需要包含的表名,当enableSqlFilter为false时,允许正则表达式(与exclude二选一配置)

  • likeTable

自3.3.0起,模糊匹配表名(与notLikeTable二选一配置)

  • exclude

需要排除的表名,当enableSqlFilter为false时,允许正则表达式

  • notLikeTable

自3.3.0起,模糊排除表名

  • entityColumnConstant

【实体】是否生成字段常量(默认 false)

  • entityBuilderModel

【实体】是否为构建者模型(默认 false),自3.3.2开始更名为 chainModel

  • chainModel(since 3.3.2)

【实体】是否为链式模型(默认 false)

  • entityLombokModel

【实体】是否为lombok模型(默认 false)

3.3.2以下版本默认生成了链式模型,3.3.2以后,默认不生成,如有需要,请开启 chainModel

  • entityBooleanColumnRemoveIsPrefix

Boolean类型字段是否移除is前缀(默认 false)

  • restControllerStyle

生成 @RestController 控制器

  • controllerMappingHyphenStyle

驼峰转连字符

  • entityTableFieldAnnotationEnable

是否生成实体时,生成字段注解

  • versionFieldName

乐观锁属性名称

#logicDeleteFieldName 逻辑删除属性名称

  • tableFillList

表填充字段

包名配置

  • parent

父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名

  • moduleName

父包模块名

  • entity

Entity包名

  • service

Service包名

  • serviceImpl

Service Impl包名

  • mapper

Mapper包名

  • xml

Mapper XML包名

  • controller

Controller包名

  • pathInfo

路径配置信息

模板配置

  • entity

Java 实体类模板

  • entityKt

Kotin 实体类模板

  • service

Service 类模板

  • serviceImpl

Service impl 实现类模板

  • mapper

mapper 模板

  • xml

mapper xml 模板

  • controller

controller 控制器模板

全局策略 globalConfig 配置

  • outputDir

生成文件的输出目录 默认值:D 盘根目录

  • fileOverride

是否覆盖已有文件 默认值:false

  • open

是否打开输出目录 默认值:true #enableCache 是否在xml中添加二级缓存配置 默认值:false

  • author

开发人员 默认值:null

  • kotlin

开启 Kotlin 模式 默认值:false

  • swagger2

开启 swagger2 模式 默认值:false

  • activeRecord

开启 ActiveRecord 模式 默认值:false

  • baseResultMap

开启 BaseResultMap 默认值:false

  • baseColumnList

开启 baseColumnList 默认值:false

  • dateType

时间类型对应策略 默认值:TIME_PACK 注意事项: 如下配置 %s 为占位符

  • entityName

实体命名方式 默认值:null 例如:%sEntity 生成 UserEntity

  • mapperName

mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao

  • xmlName

Mapper xml 命名方式 默认值:null 例如:%sDao 生成 UserDao.xml

  • serviceName

service 命名方式 默认值:null 例如:%sBusiness 生成 UserBusiness

  • serviceImplName

service impl 命名方式 默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl

  • controllerName

controller 命名方式 默认值:null 例如:%sAction 生成 UserAction

  • idType

指定生成的主键的ID类型 默认值:null

注入 injectionConfig 配置

  • map

自定义返回配置 Map 对象 该对象可以传递到模板引擎通过 cfg.xxx 引用

  • fileOutConfigList

自定义输出文件 配置 FileOutConfig 指定模板文件、输出文件达到自定义文件生成目的

  • fileCreate

自定义判断是否创建文件 实现 IFileCreate 接口 该配置用于判断某个类是否需要覆盖创建,当然你可以自己实现差异算法 merge 文件

  • initMap

注入自定义 Map 对象(注意需要setMap放进去)

更多Mybatis-Plus代码生成器配置请看官网。​ ​ MybatisPlus代码生成器官网​