# MyBatis-Plus教程 - 16 代码生成器
代码生成器也是用来生成的代码的,和 MyBatisX 相比,代码生成器不需要依赖 IDEA 插件,允许生成更多的结构和内容,生成的目录可以指定任意目录。
下面演示一下代码生成器的使用。
全新的代码生成器添加于 3.5.1 版本,且对历史版本不兼容,下面以 3.5.7
为例。
# 16.1 代码生成器的使用
# 1 添加依赖
在项目的 pom.xml 中添加依赖,引入代码生成器。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.7</version>
</dependency>
1
2
3
4
5
2
3
4
5
由于代码生成器用到了模板引擎,所以还需要引入模板引擎,MyBatis-Plus Generator 支持如下模板引擎:
- VelocityTemplateEngine(Default)
- FreemarkerTemplateEngine
- BeetlTemplateEngine
- EnjoyTemplateEngine
这里我就使用 Freemarker
了,引入 Freemarker
依赖:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.33</version>
</dependency>
1
2
3
4
5
2
3
4
5
添加完成,右键 -> Maven -> Reload Project
。
# 2 编写代码生成器代码
代码生成器的代码放在哪里都可以,只要通过 main 方法执行一下就可以。所以可以随便新建一个类,例如我这里叫 MyBatisPlusGenerator.java
。
在生产的时候指定数据库信息、生产代码的位置等信息。
package com.foooor.helloplus;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.nio.file.Paths;
import java.sql.Types;
import java.util.Collections;
public class MyBatisPlusGenerator {
public static void main(String[] args) {
// 数据库连接地址
String url = "jdbc:mysql://localhost:3306/foooor_db?useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai";
// 数据库用户名
String username = "root";
// 数据库密码
String password = "123456";
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
builder.author("baomidou") // 设置作者
.enableSwagger() // 开启 swagger 模式
.outputDir("D://"); // 指定输出目录
})
.dataSourceConfig(builder ->
builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
if (typeCode == Types.SMALLINT) {
// 自定义类型转换
return DbColumnType.INTEGER;
}
return typeRegistry.getColumnType(metaInfo);
})
)
.packageConfig(builder ->
builder.parent("com.foooor.helloplus") // 设置父包名
.moduleName("user") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")) // 设置mapperXml生成路径
)
.strategyConfig(builder ->
builder.addInclude("tb_teacher") // 设置需要生成的表名
.addTablePrefix("tb_", "tc_") // 设置过滤表前缀
)
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
上面指定了生成的目录为 D:
,那么会在 D 盘下生成,包括 controller、service、mapper 等文件。
← 15-MyBatisX插件 17-多数据源 →