参考资料
- MBG官方文档地址 http://www.mybatis.org/generator/
- MBG官方工程地址 https://github.com/mybatis/generator/releases
1. MBG简介
MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写
2. MBG With Java 环境搭建
官方参考文档:http://www.mybatis.org/generator/running/runningWithJava.html
2.1. 依赖
1 | <dependencies> |
2.2. generatorConfig.xml
1 |
|
2.3. 执行生成代码
从类路径下读取1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
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 | <commentGenerator> |
3.3. jdbcConnection 数据库连接配置
1 | <!-- 配置连接数据库的基本信息 --> |
3.4. javaModelGenerator 指定实体类生成路径
1 | <!-- 指定生成的实体类放到哪里 |
3.5. sqlMapGenerator 指定映射文件生成路径
1 | <!-- 指定生成的映射文件XxxMapper.xml放到时哪里 --> |
3.6. javaClientGenerator 指定生成Mapper接口的路径
1 | <!-- 指定生成的Mapper接口放到哪里 --> |
3.7. table 指定表与实体类的映射规则
1 | <!-- |
4. 为生成的实体类实现序列化接口
直接使用自带的插件即可1
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
生效的效果如下:1
2
3
4public 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 | package demo.mybatis.plugin; |
6.2. 配置自定义插件
1 | <plugin type="demo.mybatis.plugin.LombokPlugin"> |