MyBatis MBG 通用Mapper插件

1. MBG 通用Mapper插件 With Java 环境搭建

1.1. 依赖

在原MBG的基础上,多加一个通用mapper依赖

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
<!-- 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>
<!-- 通用mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.0</version>
</dependency>
<!-- generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>

1.2. generatorConfig.xml

添加通用Mapper插件

1
2
3
4
5
6
7
8
9
10
<!-- 指定Java文件的编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 是否使用通用 Mapper 提供的注释工具 -->
<property name="useMapperCommentGenerator" value="false"/>

<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
<property name="caseSensitive" value="true"/>
<property name="forceAnnotation" value="true"/>
</plugin>

1.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);
}

2. QBC说明

MBG<context><targetRuntime>主要有两种取值

  • MyBatis3Simple: 生成不带example的查询
  • MyBatis3:生成带example的查询

因为通用Mapper已经带有QBC的功能,所以MBG设置为MyBatis3Simple即可

panchaoxin wechat
关注我的公众号
支持一下