使用 MyBatis-Plus 代码生成器

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生

MyBatis-Plus 的目的是增强 MyBatis 的功能和操作,内置代码生成器可以为我们减少不少的工作量了,这里主要介绍 MyBatis-Plus 代码生成器的使用

代码生成器也是称作 MyBatis 的逆向工程,主要是用来生成 model、mapper 等层的代码,MyBatis 官方也有一个 MyBatis-Generator 的逆向工程,功能非常强大,但生成的代码比较臃肿,生成的 Example 类用于构造复杂的筛选条件,使用起来不友好。相比起来 MyBatis-Plus 生成的代码简洁优雅,配合 CRUD 接口和条件构造器,使用起来也方便

代码生成器

添加依赖

代码生成器的依赖

1
2
3
4
5
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>最新版本</version>
</dependency>

MyBatis-Plus 3.0.3 之后移除了自动模板引擎依赖,需要手动添加对应引擎的依赖坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- velocity 模板引擎, 默认 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>最新版本</version>
</dependency>

<!-- freemarker 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>最新版本</version>
</dependency>

<!-- beetl 模板引擎 -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>最新版本</version>
</dependency>

生成代码

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
public class Generator {

/**
* <p>
* 读取控制台内容
* </p>
*/
private static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入" + tip + ":");
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();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java"); // 生成文件的输出目录,默认D根目录
gc.setFileOverride(true); // 是否覆盖已有文件
gc.setAuthor("zou");
gc.setOpen(false); // 是否打开输出目录,默认true
gc.setEnableCache(true); // 是否在xml中添加二级缓存配置,默认false
gc.setSwagger2(true); // 开启 swagger2 模式,默认false

gc.setEntityName("%sModel");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("I%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
Properties properties = new Properties();
try {
properties.load(new FileInputStream(projectPath + "/src/main/resources/generator.properties"));
dsc.setUrl(properties.getProperty("generator.jdbc.url"));
// dsc.setSchemaName("public");
dsc.setDriverName(properties.getProperty("generator.jdbc.driver"));
dsc.setUsername(properties.getProperty("generator.jdbc.username"));
dsc.setPassword(properties.getProperty("generator.jdbc.password"));
mpg.setDataSource(dsc);
} catch (IOException e) {
throw new RuntimeException("数据源配置错误", e);
}

// 包名配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.shiyu");
pc.setEntity("model");
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) {
// 自定义输出文件名
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.setEntity();
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); // 数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
// strategy.setSuperEntityClass("com.shiyu.BaseEntity"); //自定义继承的Entity类全称,带包名
// strategy.setSuperEntityColumns(new String[] {"id","gmtCreate","gmtModified"});// 自定义基础的Entity类,公共字段
strategy.setEntityLombokModel(true); // 是否为lombok模型
strategy.setEntityBooleanColumnRemoveIsPrefix(true); // Boolean类型字段是否移除is前缀
strategy.setRestControllerStyle(true); // 生成 @RestController 控制器
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// strategy.setInclude("upms_user"); //包含的表名
strategy.setExclude("upms_role"); // 排除的表名

strategy.setControllerMappingHyphenStyle(true); // 驼峰转连字符 如 umps_user 变为 upms/user
strategy.setTablePrefix(pc.getModuleName() + "_"); // 表前缀

mpg.setStrategy(strategy);
// mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //设置模板引擎类型,默认为 velocity
// mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 切换为 freemarker 模板引擎
// mpg.setTemplateEngine(new BeetlTemplateEngine()); //切换为 beetl 模板引擎
mpg.execute();
}

}