MyBatis MBG逆向工程

参考资料

1. MBG简介

MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写

2. MBG With Java 环境搭建

官方参考文档:http://www.mybatis.org/generator/running/runningWithJava.html

2.1. 依赖

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
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!-- mybatis
MBG生成代码,本身并不需要MyBatis依赖的支持。
但是有时你会使用MBG生成MyBatis注解,这是需要MyBatis依赖的,为了生成后的文件不报错,就加上该依赖
-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>

2.2. generatorConfig.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
<context id="Mysql" targetRuntime="MyBatis3Simple"
defaultModelType="flat">
<commentGenerator>
<!-- 去掉日期注释 -->
<property name="suppressDate" value="true"/>
<!-- 去掉所有注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>

<!-- 配置连接数据库的基本信息 -->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="123456">
</jdbcConnection>

<!-- 指定生成的实体类放到哪里
targetProject: 指定根目录。"./src/main/java"
-->
<javaModelGenerator
targetProject="./src/main/java"
targetPackage="demo.mybatis.entity"/>

<!-- 指定生成的映射文件XxxMapper.xml放到时哪里 -->
<sqlMapGenerator
targetProject="./src/main/java"
targetPackage="demo.mybatis.mapper"/>

<!-- 指定生成的Mapper接口放到哪里 -->
<javaClientGenerator
targetProject="./src/main/java"
targetPackage="demo.mybatis.mapper"
type="XMLMAPPER"/>

<!--
table: 指定表和实体类之间的逆向生成规则
tableName: 指定表名。"%"表示数据库中所有表都参与逆向工程,此时使用默认规则
domainObjectName: 指定实体类的名称。
如果不指定,默认是下划线转大驼峰。例如tableName="hello_world",那么实体类名就是"HelloWorld"
-->
<table tableName="book"/>
<table tableName="author"/>
<!--<table tableName="book" domainObjectName="Employee">-->
<!--&lt;!&ndash; 配置主键生成策略 &ndash;&gt;-->
<!--<generatedKey column="emp_id" sqlStatement="Mysql" identity="true"/>-->
<!--</table>-->
</context>
</generatorConfiguration>

2.3. 执行生成代码

从类路径下读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void test() throws Exception {
// MBG执行过程中的警告信息
List<String> warnings = new ArrayList<String>();
// 覆盖原文件
boolean overwrite = true;
// 读取配置
InputStream in = this.getClass().getClassLoader().getResourceAsStream("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(in);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
// 创建MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
// 执行生成代码
myBatisGenerator.generate(null);
// 输出警告信息
warnings.forEach(System.out::println);
}

从本地磁盘读取

1
2
3
4
5
6
7
8
9
10
11
@Test
public void test() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}

3. MBG 配置文件

你至少需要指定以下信息:

  • <jdbcConnection> 指定连接数据库的配置信息
  • <javaModelGenerator> 指定生成的实体类放到哪里
  • <sqlMapGenerator> 指定生成的映射文件XxxMapper.xml放到哪里
  • <table> 至少要1个table配置
  • <javaClientGenerator> 可选配置。指定生成的XxxMapper接口放到哪里

3.1. context

targetRuntime属性

  • MyBatis3Simple:只生成基本的CRUD,没有byExample方法
  • MyBatis3:生成CRUD,还有byExample方法

3.2. commentGenerator 去掉生成的注释

1
2
3
4
5
6
<commentGenerator>
<!-- 去掉日期注释 -->
<property name="suppressDate" value="true"/>
<!-- 去掉所有注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>

3.3. jdbcConnection 数据库连接配置

1
2
3
4
5
6
7
<!-- 配置连接数据库的基本信息 -->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="123456">
</jdbcConnection>

3.4. javaModelGenerator 指定实体类生成路径

1
2
3
4
5
6
<!-- 指定生成的实体类放到哪里
targetProject: 指定根目录。"./src/main/java"
-->
<javaModelGenerator
targetProject="./src/main/java"
targetPackage="demo.mybatis.entity"/>

3.5. sqlMapGenerator 指定映射文件生成路径

1
2
3
4
<!-- 指定生成的映射文件XxxMapper.xml放到时哪里 -->
<sqlMapGenerator
targetProject="./src/main/java"
targetPackage="demo.mybatis.mapper"/>

3.6. javaClientGenerator 指定生成Mapper接口的路径

1
2
3
4
5
<!-- 指定生成的Mapper接口放到哪里 -->
<javaClientGenerator
targetProject="./src/main/java"
targetPackage="demo.mybatis.mapper"
type="XMLMAPPER"/>

3.7. table 指定表与实体类的映射规则

1
2
3
4
5
6
7
8
<!--
table: 指定表和实体类之间的逆向生成规则
tableName: 指定表名。"%"表示数据库中所有表都参与逆向工程,此时使用默认规则
domainObjectName: 指定实体类的名称。
如果不指定,默认是下划线转大驼峰。例如tableName="hello_world",那么实体类名就是"HelloWorld"
-->
<table tableName="book"/>
<table tableName="author"/>

4. 为生成的实体类实现序列化接口

直接使用自带的插件即可

1
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

生效的效果如下:

1
2
3
4
public class Author implements Serializable {
// ......
private static final long serialVersionUID = 1L;
}

5. 自动生成主键生成策略

设置主键生成

1
2
3
4
5
6
7
8
9
<table tableName="author">
<!-- 配置主键生成策略
column: 数据库中的主键列名
sqlStatement: 可选值是固定的。值为"MySql"时,代表采取SELECT LAST_INSERT_ID()获取主键
identity: true对应<selectKey>的order
如果
-->
<generatedKey column="author_id" sqlStatement="MySql" identity="true"/>
</table>

生成后的效果

1
2
3
<selectKey keyProperty="authorId" order="BEFORE" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>

6. 整合Lombok

6.1. 自定义MBG插件

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
package demo.mybatis.plugin;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

public class LombokPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
}

@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 添加domain的import
topLevelClass.addImportedType("lombok.Data");
topLevelClass.addImportedType("lombok.Builder");
topLevelClass.addImportedType("lombok.NoArgsConstructor");
topLevelClass.addImportedType("lombok.AllArgsConstructor");

// 添加domain的注解
topLevelClass.addAnnotation("@Data");
topLevelClass.addAnnotation("@Builder");
topLevelClass.addAnnotation("@NoArgsConstructor");
topLevelClass.addAnnotation("@AllArgsConstructor");

return true;
}


@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
// 不生成setter
return false;
}

@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
// 不生成getter
return false;
}
}

6.2. 配置自定义插件

1
2
<plugin type="demo.mybatis.plugin.LombokPlugin">
</plugin>
panchaoxin wechat
关注我的公众号
支持一下