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>
<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>
<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 {
@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");
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8");
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() {
}
};
String templatePath = "/templates/mapper.xml.ftl";
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@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);
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
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();
}
}
打开目录就可以看到生成的文件
基于SpringBoot整合Mybatis-Plus代码生成器
创建SpringBoot项目
引入依赖
<?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/>
</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>
<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>
<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 {
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 + "!");
}
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.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() {
}
};
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.setEntityLombokModel(true);
strategy.setInclude(scanner("表名"));
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
测试并验证
代码生成器常用配置
数据源 dataSourceConfig 配置
数据库
信息查询类
默认由 dbType 类型决定选择对应数据库内置实现
实现 IDbQuery 接口自定义数据库查询 SQL 语句 定制化返回自己需要的内容
数据库
类型
该类内置了常用的数据库类型【必须】
数据库
schema name
例如 PostgreSQL 可指定为 public
类型转换
默认由 dbType 类型决定选择对应
数据库
内置实现
实现 ITypeConvert 接口自定义数据库 字段类型 转换为自己需要的 java 类型,内置转换类型无法满足可实现 IColumnType 接口自定义
驱动连接的URL
驱动名称
数据库
连接用户名
数据库
连接密码
数据库表配置
是否大写命名
是否跳过视图
数据库
表映射到实体的命名策略
数据库
表字段映射到实体的命名策略, 未指定按照 naming 执行
表前缀
字段前缀
自定义继承的Entity类全称,带包名
自定义基础的Entity类,公共字段
自定义继承的Mapper类全称,带包名
自定义继承的Service类全称,带包名
自定义继承的ServiceImpl类全称,带包名
自定义继承的Controller类全称,带包名
-
enableSqlFilter(since 3.3.1)
默认激活进行sql模糊表名匹配关闭之后likeTable与notLikeTable将失效,include和exclude将使用内存过滤
如果有sql语法兼容性问题的话,请手动设置为false
已知无法使用:MyCat中间件, 支持情况传送门(opens new window)
需要包含的表名,当enableSqlFilter为false时,允许正则表达式(与exclude二选一配置)
自3.3.0起,模糊匹配表名(与notLikeTable二选一配置)
需要排除的表名,当enableSqlFilter为false时,允许正则表达式
自3.3.0起,模糊排除表名
【实体】是否生成字段常量(默认 false)
【实体】是否为构建者模型(默认 false),自3.3.2开始更名为 chainModel
【实体】是否为链式模型(默认 false)
【实体】是否为lombok模型(默认 false)
3.3.2以下版本默认生成了链式模型,3.3.2以后,默认不生成,如有需要,请开启 chainModel
-
entityBooleanColumnRemoveIsPrefix
Boolean类型字段是否移除is前缀(默认 false)
生成 @RestController 控制器
-
controllerMappingHyphenStyle
驼峰转连字符
-
entityTableFieldAnnotationEnable
是否生成实体时,生成字段注解
乐观锁属性名称
#logicDeleteFieldName
逻辑删除属性名称
表填充字段
包名配置
父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
父包模块名
Entity包名
Service包名
Service Impl包名
Mapper包名
Mapper XML包名
Controller包名
路径配置信息
模板配置
Java 实体类模板
Kotin 实体类模板
Service 类模板
Service impl 实现类模板
mapper 模板
mapper xml 模板
controller 控制器模板
全局策略 globalConfig 配置
生成文件的输出目录
默认值:D 盘根目录
是否覆盖已有文件
默认值:false
是否打开输出目录
默认值:true
#enableCache
是否在xml中添加二级缓存配置
默认值:false
开发人员
默认值:null
开启 Kotlin 模式
默认值:false
开启 swagger2 模式
默认值:false
开启 ActiveRecord 模式
默认值:false
开启 BaseResultMap
默认值:false
开启 baseColumnList
默认值:false
时间类型对应策略
默认值:TIME_PACK
注意事项:
如下配置 %s 为占位符
实体命名方式
默认值:null 例如:%sEntity 生成 UserEntity
mapper 命名方式
默认值:null 例如:%sDao 生成 UserDao
Mapper xml 命名方式
默认值:null 例如:%sDao 生成 UserDao.xml
service 命名方式
默认值:null 例如:%sBusiness 生成 UserBusiness
service impl 命名方式
默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
controller 命名方式
默认值:null 例如:%sAction 生成 UserAction
指定生成的主键的ID类型
默认值:null
注入 injectionConfig 配置
自定义返回配置 Map 对象
该对象可以传递到模板引擎通过 cfg.xxx 引用
自定义输出文件
配置 FileOutConfig 指定模板文件、输出文件达到自定义文件生成目的
自定义判断是否创建文件
实现 IFileCreate 接口
该配置用于判断某个类是否需要覆盖创建,当然你可以自己实现差异算法 merge 文件
注入自定义 Map 对象(注意需要setMap放进去)
更多Mybatis-Plus代码生成器配置请看官网。
MybatisPlus代码生成器官网