Skip to content

Commit d4a6089

Browse files
author
hewei
committed
新增Mapper注解插件
1 parent 8cd7181 commit d4a6089

File tree

6 files changed

+325
-0
lines changed

6 files changed

+325
-0
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
* [数据ModelCloneable插件(ModelCloneablePlugin)](#20-数据ModelCloneable插件)
3838
* [状态枚举生成插件(EnumTypeStatusPlugin)](#21-状态枚举生成插件)
3939
* [增量插件(IncrementPlugin)](#22-增量插件)
40+
* [Mapper注解插件(MapperAnnotationPlugin)](#23-Mapper注解插件)
4041

4142
---------------------------------------
4243
Maven引用:
@@ -1633,4 +1634,19 @@ public class Test {
16331634
this.tbMapper.updateByPrimaryKey(tb);
16341635
}
16351636
}
1637+
```
1638+
### 23. Mapper注解插件
1639+
对官方的([MapperAnnotationPlugin](http://www.mybatis.org/generator/reference/plugins.html))增强,可自定义附加@Repository注解(IDEA工具对@Mapper注解支持有问题,使用@Autowired会报无法找到对应bean,附加@Repository后解决);
1640+
1641+
插件:
1642+
```xml
1643+
<xml>
1644+
<!-- Mapper注解插件 -->
1645+
<plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin">
1646+
<!-- @Mapper 默认开启 -->
1647+
<property name="@Mapper" value="true"/>
1648+
<!-- @Repository 默认关闭,开启后解决IDEA工具@Autowired报错 -->
1649+
<property name="@Repository" value="false"/>
1650+
</plugin>
1651+
</xml>
16361652
```
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* Copyright (c) 2019.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.itfsw.mybatis.generator.plugins;
18+
19+
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
20+
import org.mybatis.generator.api.IntrospectedTable;
21+
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
22+
import org.mybatis.generator.api.dom.java.Interface;
23+
import org.mybatis.generator.api.dom.java.TopLevelClass;
24+
import org.mybatis.generator.internal.util.StringUtility;
25+
26+
import java.util.*;
27+
28+
/**
29+
* ---------------------------------------------------------------------------
30+
*
31+
* ---------------------------------------------------------------------------
32+
* @author: hewei
33+
* @time:2019/7/9 14:30
34+
* ---------------------------------------------------------------------------
35+
*/
36+
public class MapperAnnotationPlugin extends BasePlugin {
37+
private final static Map<String, String> ANNOTATION_IMPORTS;
38+
39+
static {
40+
ANNOTATION_IMPORTS = new HashMap<>();
41+
ANNOTATION_IMPORTS.put("@Mapper", "org.apache.ibatis.annotations.Mapper");
42+
ANNOTATION_IMPORTS.put("@Repository", "org.springframework.stereotype.Repository");
43+
}
44+
45+
private List<String> annotations;
46+
47+
/**
48+
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
49+
* @param introspectedTable
50+
* @return
51+
*/
52+
@Override
53+
public void initialized(IntrospectedTable introspectedTable) {
54+
super.initialized(introspectedTable);
55+
56+
this.annotations = new ArrayList<>();
57+
Properties properties = this.getProperties();
58+
boolean findMapper = false;
59+
for (Object key : properties.keySet()) {
60+
String annotation = key.toString().trim();
61+
if (annotation.startsWith("@Mapper")) {
62+
findMapper = true;
63+
}
64+
65+
if (StringUtility.isTrue(properties.getProperty(key.toString()))) {
66+
this.annotations.add(annotation);
67+
}
68+
}
69+
70+
if (!findMapper) {
71+
this.annotations.add(0, "@Mapper");
72+
}
73+
}
74+
75+
/**
76+
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
77+
* @param interfaze
78+
* @param topLevelClass
79+
* @param introspectedTable
80+
* @return
81+
*/
82+
@Override
83+
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
84+
for (String annotation : this.annotations) {
85+
if (annotation.equals("@Mapper")) {
86+
if (introspectedTable.getTargetRuntime() == IntrospectedTable.TargetRuntime.MYBATIS3) {
87+
// don't need to do this for MYBATIS3_DSQL as that runtime already adds this annotation
88+
interfaze.addImportedType(new FullyQualifiedJavaType(ANNOTATION_IMPORTS.get(annotation)));
89+
interfaze.addAnnotation(annotation);
90+
}
91+
} else if (ANNOTATION_IMPORTS.get(annotation) != null) {
92+
interfaze.addImportedType(new FullyQualifiedJavaType(ANNOTATION_IMPORTS.get(annotation)));
93+
interfaze.addAnnotation(annotation);
94+
}
95+
}
96+
97+
return true;
98+
}
99+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
* Copyright (c) 2019.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.itfsw.mybatis.generator.plugins;
18+
19+
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
20+
import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool;
21+
import org.junit.Assert;
22+
import org.junit.BeforeClass;
23+
import org.junit.Test;
24+
import org.mybatis.generator.api.GeneratedJavaFile;
25+
import org.mybatis.generator.api.MyBatisGenerator;
26+
import org.mybatis.generator.api.dom.java.CompilationUnit;
27+
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
28+
import org.mybatis.generator.api.dom.java.Interface;
29+
30+
/**
31+
* ---------------------------------------------------------------------------
32+
*
33+
* ---------------------------------------------------------------------------
34+
* @author: hewei
35+
* @time:2019/7/9 14:46
36+
* ---------------------------------------------------------------------------
37+
*/
38+
public class MapperAnnotationPluginTest {
39+
40+
/**
41+
* 初始化
42+
*/
43+
@BeforeClass
44+
public static void init() throws Exception {
45+
DBHelper.createDB("scripts/MapperAnnotationPlugin/init.sql");
46+
}
47+
48+
/**
49+
* 测试默认配置
50+
*/
51+
@Test
52+
public void testDefault() throws Exception{
53+
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/MapperAnnotationPlugin/mybatis-generator.xml");
54+
MyBatisGenerator myBatisGenerator = tool.generate();
55+
56+
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
57+
CompilationUnit compilationUnit = file.getCompilationUnit();
58+
if (compilationUnit instanceof Interface && compilationUnit.getType().getShortName().endsWith("Mapper")) {
59+
Interface interfaze = (Interface) compilationUnit;
60+
61+
Assert.assertEquals(interfaze.getAnnotations().size(), 1);
62+
Assert.assertEquals(interfaze.getAnnotations().get(0), "@Mapper");
63+
Assert.assertTrue(interfaze.getImportedTypes().contains(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper")));
64+
}
65+
}
66+
}
67+
68+
/**
69+
* 测试配置Repository
70+
* @throws Exception
71+
*/
72+
@Test
73+
public void testWithRepository() throws Exception{
74+
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/MapperAnnotationPlugin/mybatis-generator-with-repository.xml");
75+
MyBatisGenerator myBatisGenerator = tool.generate();
76+
77+
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
78+
CompilationUnit compilationUnit = file.getCompilationUnit();
79+
if (compilationUnit instanceof Interface && compilationUnit.getType().getShortName().endsWith("Mapper")) {
80+
Interface interfaze = (Interface) compilationUnit;
81+
82+
Assert.assertEquals(interfaze.getAnnotations().size(), 2);
83+
Assert.assertEquals(interfaze.getAnnotations().get(0), "@Mapper");
84+
Assert.assertEquals(interfaze.getAnnotations().get(1), "@Repository");
85+
Assert.assertTrue(interfaze.getImportedTypes().contains(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper")));
86+
Assert.assertTrue(interfaze.getImportedTypes().contains(new FullyQualifiedJavaType("org.springframework.stereotype.Repository")));
87+
}
88+
}
89+
}
90+
91+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
Navicat MySQL Data Transfer
3+
4+
Source Server : localhost
5+
Source Server Version : 50617
6+
Source Host : localhost:3306
7+
Source Database : mybatis-generator-plugin
8+
9+
Target Server Type : MYSQL
10+
Target Server Version : 50617
11+
File Encoding : 65001
12+
13+
Date: 2017-07-03 17:34:11
14+
*/
15+
16+
SET FOREIGN_KEY_CHECKS=0;
17+
18+
-- ----------------------------
19+
-- Table structure for tb
20+
-- ----------------------------
21+
DROP TABLE IF EXISTS `tb`;
22+
CREATE TABLE `tb` (
23+
`id` bigint(20) NOT NULL COMMENT '注释1',
24+
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
25+
`field2` int(11) DEFAULT NULL,
26+
PRIMARY KEY (`id`)
27+
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
~ Copyright (c) 2019.
4+
~
5+
~ Licensed under the Apache License, Version 2.0 (the "License");
6+
~ you may not use this file except in compliance with the License.
7+
~ You may obtain a copy of the License at
8+
~
9+
~ http://www.apache.org/licenses/LICENSE-2.0
10+
~
11+
~ Unless required by applicable law or agreed to in writing, software
12+
~ distributed under the License is distributed on an "AS IS" BASIS,
13+
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
~ See the License for the specific language governing permissions and
15+
~ limitations under the License.
16+
-->
17+
18+
<!DOCTYPE generatorConfiguration
19+
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
20+
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
21+
<generatorConfiguration>
22+
<properties resource="db.properties"/>
23+
<!--导入属性配置 -->
24+
<context id="default" targetRuntime="MyBatis3">
25+
<!-- 插件 -->
26+
<plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin">
27+
<property name="@Repository" value="true"/>
28+
</plugin>
29+
30+
<!--jdbc的数据库连接 -->
31+
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}"/>
32+
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
33+
targetPackage 指定生成的model生成所在的包名
34+
targetProject 指定在该项目下所在的路径 -->
35+
<javaModelGenerator targetPackage="" targetProject=""/>
36+
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
37+
<sqlMapGenerator targetPackage="" targetProject=""/>
38+
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
39+
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
40+
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
41+
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
42+
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
43+
44+
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
45+
<table tableName="tb"/>
46+
</context>
47+
</generatorConfiguration>
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
~ Copyright (c) 2019.
4+
~
5+
~ Licensed under the Apache License, Version 2.0 (the "License");
6+
~ you may not use this file except in compliance with the License.
7+
~ You may obtain a copy of the License at
8+
~
9+
~ http://www.apache.org/licenses/LICENSE-2.0
10+
~
11+
~ Unless required by applicable law or agreed to in writing, software
12+
~ distributed under the License is distributed on an "AS IS" BASIS,
13+
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
~ See the License for the specific language governing permissions and
15+
~ limitations under the License.
16+
-->
17+
18+
<!DOCTYPE generatorConfiguration
19+
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
20+
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
21+
<generatorConfiguration>
22+
<properties resource="db.properties"/>
23+
<!--导入属性配置 -->
24+
<context id="default" targetRuntime="MyBatis3">
25+
<!-- 插件 -->
26+
<plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin"/>
27+
28+
<!--jdbc的数据库连接 -->
29+
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}"/>
30+
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
31+
targetPackage 指定生成的model生成所在的包名
32+
targetProject 指定在该项目下所在的路径 -->
33+
<javaModelGenerator targetPackage="" targetProject=""/>
34+
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
35+
<sqlMapGenerator targetPackage="" targetProject=""/>
36+
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
37+
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
38+
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
39+
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
40+
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
41+
42+
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
43+
<table tableName="tb"/>
44+
</context>
45+
</generatorConfiguration>

0 commit comments

Comments
 (0)