Compare commits

...
30 Commits
Author SHA1 Message Date
hewei a1735681d5 [maven-release-plugin] prepare release V1.0.11 2017-06-09 17:00:38 +08:00
hewei 0e244ee3f8 新增注释插件 2017-06-09 16:59:32 +08:00
hewei ffcbdc12cb 新增注释插件 2017-06-09 15:36:02 +08:00
hewei ccbdad7eba 替换默认注释工具 2017-06-09 14:45:38 +08:00
hewei 46793b3601 新增注释插件 2017-06-09 13:57:42 +08:00
hewei cc043ac38c 删除遗留的测试信息 2017-06-08 13:32:01 +08:00
hewei c4b2769540 优化注释生成工具实现逻辑,实现用户定制输出不影响 2017-06-08 10:51:02 +08:00
hewei 4aef323383 [maven-release-plugin] prepare for next development iteration 2017-06-07 17:32:54 +08:00
hewei 672b704452 [maven-release-plugin] prepare release V1.0.10 2017-06-07 17:31:59 +08:00
hewei 27b7734da1 v1.0.10文档 2017-06-07 17:26:57 +08:00
hewei 46069323ed v1.0.10文档 2017-06-06 18:36:47 +08:00
hewei 2e697df7d9 插件重命名 2017-06-06 17:55:06 +08:00
hewei 719e862712 插件重命名 2017-06-06 17:54:47 +08:00
hewei 0b63df6f7a 插件重命名 2017-06-06 17:50:42 +08:00
hewei efc26b78b4 新增: table 重命名插件 2017-06-06 17:50:24 +08:00
hewei 88d480e2ca [maven-release-plugin] prepare for next development iteration 2017-05-19 18:49:13 +08:00
hewei 56addb28f8 [maven-release-plugin] prepare release V1.0.9 2017-05-19 18:48:50 +08:00
hewei 0c276b1553 v1.0.9文档修正 2017-05-19 18:46:46 +08:00
hewei 46d0b154d9 bug fixed: 有种情况下ModelBaseRecordClass不会生成不包含BLOBs的构造方法,造成selectOneByExample返回结果找不到对应的构造方法异常 2017-05-19 18:29:09 +08:00
hewei e133a04108 bug fixed: 对于是否实现WithBLOBs方法,判断基准是是否表存在BLOBs类型字段 2017-05-19 10:56:39 +08:00
hewei a47d4510c5 bug fixed: 修正使用autoDelimitKeywords过滤关键词造成的field前后加了特殊字符的问题 2017-05-18 17:59:04 +08:00
hewei a1bdd5f1cd Table 前缀插件,用来解决多数据源表名相同时冲突问题 2017-05-18 17:08:52 +08:00
hewei 4f14290789 对于Model生成WithBLOBs类时,upsert插件实现行为和官方插件保持一致 2017-05-17 18:58:26 +08:00
hewei 2b88b81d49 移除一些过时的插件 2017-05-17 18:31:12 +08:00
hewei 2571f1c507 对于Model生成WithBLOBs类时,upsert插件实现行为和官方插件保持一致 2017-05-17 18:30:51 +08:00
hewei 30a3539fc4 对于Model生成WithBLOBs类时,SelectOneByExample插件实现行为和官方插件保持一致 2017-05-17 16:51:38 +08:00
hewei 1f5e57dc51 对于Model生成WithBLOBs类时,SelectOneByExample插件实现行为和官方插件保持一致 2017-05-17 16:49:49 +08:00
hewei 9b500d994a 解决Model生成WithBLOBs类时,Column枚举在WithBLOBs类也应该存在的问题 2017-05-17 16:07:36 +08:00
hewei 8ff3ee9988 解决Model生成WithBLOBs类时,ModelBuilder未按类字段对应生成正确Builder字段赋值方法的BUG 2017-05-17 16:03:54 +08:00
hewei 2f9fb379fb [maven-release-plugin] prepare for next development iteration 2017-05-10 10:31:46 +08:00
20 changed files with 2132 additions and 779 deletions
+436 -16
View File
@@ -14,6 +14,9 @@
* [数据Model属性对应Column获取插件(ModelColumnPlugin)](#8-数据model属性对应column获取插件)
* [存在即更新插件(UpsertPlugin)](#9-存在即更新插件)
* [Selective选择插入更新增强插件(SelectiveEnhancedPlugin)](#10-selective选择插入更新增强插件)
* [Table增加前缀插件(TablePrefixPlugin)](#11-table增加前缀插件)
* [Table重命名插件(TableRenamePlugin)](#12-table重命名插件)
* [自定义注释插件(CommentPlugin)](#13-自定义注释插件)
---------------------------------------
Maven引用:
@@ -21,7 +24,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.8</version>
<version>1.0.11</version>
</dependency>
```
---------------------------------------
@@ -36,13 +39,23 @@ Maven引用:
```java
public interface TbMapper {
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
Tb selectOneByExample(TbExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
// Model WithBLOBs 时才有
TbWithBLOBs selectOneByExampleWithBLOBs(TbExample example);
}
```
### 2. MySQL分页插件
@@ -56,28 +69,29 @@ public interface TbMapper {
```java
public class TbExample {
/**
* 这是Mybatis Generator拓展插件生成的属性(请勿删除).
* This field was generated by MyBatis Generator.
* This field corresponds to the database table tb
*
* @mbg.generated
* @author hewei
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
protected Integer offset;
/**
* 这是Mybatis Generator拓展插件生成的属性(请勿删除).
* This field was generated by MyBatis Generator.
* This field corresponds to the database table tb
*
* @mbg.generated
* @author hewei
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
protected Integer rows;
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table rc_user_token
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public TbExample limit(Integer rows) {
this.rows = rows;
@@ -85,11 +99,11 @@ public class TbExample {
}
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table rc_user_token
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public TbExample limit(Integer offset, Integer rows) {
this.offset = offset;
@@ -98,11 +112,11 @@ public class TbExample {
}
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public TbExample page(Integer page, Integer pageSize) {
this.offset = page * pageSize;
@@ -478,12 +492,20 @@ public class Test {
.example()
);
// upsertByExampleSelective 用法类似
// 当Model WithBLOBs 存在时上述方法增加对应的 WithBLOBs 方法,举例如下:
TbWithBLOBs tb3 = new Tb.Builder()
.field1(1)
.field2("xx0")
.delFlag(Tb.DEL_FLAG_ON)
.build();
int k6 = this.tbMapper.upsertWithBLOBs(tb);
}
}
```
### 10. Selective选择插入更新增强插件
项目中往往需要指定某些字段进行插入或者更新,或者把某些字段进行设置null处理,这种情况下原生xxxSelective方法往往不能达到需求,因为它的判断条件是对象字段是否为null,这种情况下可使用该插件对xxxSelective方法进行增强。
WAREN:配置插件时请把插件配置在所有插件末尾最后执行,这样才能把上面提供的某些插件的Selective方法也同时增强!
>warning:配置插件时请把插件配置在所有插件末尾最后执行,这样才能把上面提供的某些插件的Selective方法也同时增强!
插件:
```xml
@@ -530,4 +552,402 @@ public class Test {
);
}
}
```
### 11. Table增加前缀插件
项目中有时会遇到配置多数据源对应多业务的情况,这种情况下可能会出现不同数据源出现重复表名,造成异常冲突。
该插件允许为表增加前缀,改变最终生成的Model、Mapper、Example类名以及xml名。
>warning: 请原谅我蹩脚的英文水平,一直没发现插件名称错了,1.0.9版本错误命名为TableSuffixPlugin,属性为suffix请新版本用户对应修正!
插件:
```xml
<xml>
<!-- Table增加前缀插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.TablePrefixPlugin">
<!-- 这里配置的是全局表前缀,当然在table中配置的值会覆盖该全局配置 -->
<property name="prefix" value="Cm"/>
</plugin>
<table tableName="tb">
<!-- 这里可以单独表配置前缀,覆盖全局配置 -->
<property name="suffix" value="Db1"/>
</table>
</xml>
```
使用:
```java
public class Test {
public static void main(String[] args) {
// Tb 表对应的Model、Mapper、Example类都增加了Db1的前缀
// Model类名: Tb -> Db1Tb
// Mapper类名: TbMapper -> Db1TbMapper
// Example类名: TbExample -> Db1TbExample
// xml文件名: TbMapper.xml -> Db1TbMapper.xml
}
}
```
### 12. Table重命名插件
插件由来:
记得才开始工作时某个隔壁项目组的坑爹项目,由于某些特定的原因数据库设计表名为t1~tn,字段名为f1~fn。
这种情况下如何利用Mybatis Generator生成可读的代码呢,字段可以用columnOverride来替换,Model、Mapper等则需要使用domainObjectName+mapperName来实现方便辨识的代码。
>该插件解决:domainObjectName+mapperName?好吧我想简化一下,所以直接使用tableOverride(仿照columnOverride)来实现便于配置的理解。
某些DBA喜欢在数据库设计时使用t_、f_这种类似的设计([[issues#4]](https://github.com/itfsw/mybatis-generator-plugin/issues/4)),
这种情况下我们就希望能有类似[columnRenamingRule](http://www.mybatis.org/generator/configreference/columnRenamingRule.html)这种重命名插件来修正最终生成的Model、Mapper等命名。
>该插件解决:使用正则替换table生成的Model、Example、Mapper等命名。
>warning:和插件[Table增加前缀插件](#11-table增加前缀插件)联合使用时,需注意顺序问题。
插件:
```xml
<xml>
<!-- Table重命名插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.TablePrefixPlugin">
<!-- 可根据具体需求确定是否配置 -->
<property name="searchString" value="^T"/>
<property name="replaceString" value=""/>
</plugin>
<table tableName="tb">
<!-- 这个优先级最高,会忽略searchString、replaceString的配置 -->
<property name="tableOverride" value="TestDb"/>
</table>
</xml>
```
使用:
```java
public class Test {
public static void main(String[] args) {
// 1. 使用searchString和replaceString时,和Mybatis Generator一样使用的是java.util.regex.Matcher.replaceAll去进行正则替换
// 表: T_USER
// Model类名: TUser -> User
// Mapper类名: TUserMapper -> UserMapper
// Example类名: TUserExample -> UserExample
// xml文件名: TUserMapper.xml -> UserMapper.xml
// 2. 使用表tableOverride时,该配置优先级最高
// 表: T_BOOK
// Model类名: TBook -> TestDb
// Mapper类名: TBookMapper -> TestDbMapper
// Example类名: TBookExample -> TestDbExample
// xml文件名: TBookMapper.xml -> TestDbMapper.xml
}
}
```
### 12. 自定义注释插件
Mybatis Generator是原生支持自定义注释的(commentGenerator配置type属性),但使用比较麻烦需要自己实现CommentGenerator接口并打包配置赖等等。
该插件借助freemarker极佳的灵活性实现了自定义注释的快速配置。
>warning: 下方提供了一个参考模板,需要注意${mgb}的输出,因为Mybatis Generator就是通过该字符串判断是否为自身生成代码进行覆盖重写。
>warning: 请注意拷贝参考模板注释前方空格,idea等工具拷贝进去后自动格式化会造成格式错乱。
>warning: 模板引擎采用的是freemarker所以一些freemarker指令参数(如:<#if xx></#if>、${.now?string("yyyy-MM-dd HH:mm:ss")})都是可以使用的,请自己尝试。
| 注释ID | 传入参数 | 备注 |
| ----- | ----- | ---- |
| addJavaFileComment | mgb<br>compilationUnit | Java文件注释 |
| addComment | mgb<br>xmlElement | Xml节点注释 |
| addRootComment | mgb<br>rootElement | Xml根节点注释 |
| addFieldComment | mgb<br>field<br>introspectedTable<br>introspectedColumn | Java 字段注释(非生成Model对应表字段时,introspectedColumn可能不存在) |
| addModelClassComment | mgb<br>topLevelClass<br>introspectedTable | 表Model类注释 |
| addClassComment | mgb<br>innerClass<br>introspectedTable | 类注释 |
| addEnumComment | mgb<br>innerEnum<br>introspectedTable | 枚举注释 |
| addInterfaceComment | mgb<br>innerInterface<br>introspectedTable | 接口注释(itfsw插件新增类型) |
| addGetterComment | mgb<br>method<br>introspectedTable<br>introspectedColumn | getter方法注释(introspectedColumn可能不存在) |
| addSetterComment | mgb<br>method<br>introspectedTable<br>introspectedColumn | getter方法注释(introspectedColumn可能不存在) |
| addGeneralMethodComment | mgb<br>method<br>introspectedTable | 方法注释 |
插件:
```xml
<xml>
<!-- 自定义注释插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin">
<!-- 自定义模板路径 -->
<property name="template" value="src/main/resources/mybatis-generator-comment.ftl" />
</plugin>
</xml>
```
使用(参考模板):
```xml
<?xml version="1.0" encoding="UTF-8"?>
<template>
<!-- #############################################################################################################
/**
* This method is called to add a file level comment to a generated java file. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the Java file merge function in Eclipse
* does not deal with this comment. If you run the generator repeatedly, you will only retain the comment from the
* initial run.
* <p>
*
* The default implementation does nothing.
*
* @param compilationUnit
* the compilation unit
*/
-->
<comment ID="addJavaFileComment"></comment>
<!-- #############################################################################################################
/**
* This method should add a suitable comment as a child element of the specified xmlElement to warn users that the
* element was generated and is subject to regeneration.
*
* @param xmlElement
* the xml element
*/
-->
<comment ID="addComment"><![CDATA[
<!--
WARNING - ${mgb}
This element is automatically generated by MyBatis Generator, do not modify.
@project https://github.com/itfsw/mybatis-generator-plugin
-->
]]></comment>
<!-- #############################################################################################################
/**
* This method is called to add a comment as the first child of the root element. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the XML file merge function does not deal
* with this comment. If you run the generator repeatedly, you will only retain the comment from the initial run.
* <p>
*
* The default implementation does nothing.
*
* @param rootElement
* the root element
*/
-->
<comment ID="addRootComment"></comment>
<!-- #############################################################################################################
/**
* This method should add a Javadoc comment to the specified field. The field is related to the specified table and
* is used to hold the value of the specified column.
* <p>
*
* <b>Important:</b> This method should add a the nonstandard JavaDoc tag "@mbg.generated" to the comment. Without
* this tag, the Eclipse based Java merge feature will fail.
*
* @param field
* the field
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addFieldComment"><![CDATA[
<#if introspectedColumn??>
/**
<#if introspectedColumn.remarks?? && introspectedColumn.remarks != ''>
* Database Column Remarks:
<#list introspectedColumn.remarks?split("\n") as remark>
* ${remark}
</#list>
</#if>
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds a comment for a model class. The Java code merger should
* be notified not to delete the entire class in case any manual
* changes have been made. So this method will always use the
* "do not delete" annotation.
*
* Because of difficulties with the Java file merger, the default implementation
* of this method should NOT add comments. Comments should only be added if
* specifically requested by the user (for example, by enabling table remark comments).
*
* @param topLevelClass
* the top level class
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addModelClassComment"><![CDATA[
/**
<#if introspectedTable.remarks?? && introspectedTable.remarks != ''>
* Database Table Remarks:
<#list introspectedTable.remarks?split("\n") as remark>
* ${remark}
</#list>
</#if>
*
* This class was generated by MyBatis Generator.
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb} do_not_delete_during_merge
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the inner class comment.
*
* @param innerClass
* the inner class
* @param introspectedTable
* the introspected table
* @param markAsDoNotDelete
* the mark as do not delete
*/
-->
<comment ID="addClassComment"><![CDATA[
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}<#if markAsDoNotDelete?? && markAsDoNotDelete> do_not_delete_during_merge</#if>
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the enum comment.
*
* @param innerEnum
* the inner enum
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addEnumComment"><![CDATA[
/**
* This enum was generated by MyBatis Generator.
* This enum corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the interface comment.
*
* @param innerInterface
* the inner interface
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addInterfaceComment"><![CDATA[
/**
* This interface was generated by MyBatis Generator.
* This interface corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the getter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addGetterComment"><![CDATA[
<#if introspectedColumn??>
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* @return the value of ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the field ${method.name?replace("get","")?replace("is", "")?uncap_first}
*
* @return the value of field ${method.name?replace("get","")?replace("is", "")?uncap_first}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds the setter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addSetterComment"><![CDATA[
<#if introspectedColumn??>
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* @param ${method.parameters[0].name} the value for ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the field ${method.name?replace("set","")?uncap_first}
*
* @param ${method.parameters[0].name} the value for field ${method.name?replace("set","")?uncap_first}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds the general method comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addGeneralMethodComment"><![CDATA[
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
</template>
```
+14 -2
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.8</version>
<version>1.0.11</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -41,6 +41,18 @@
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.26-incubating</version>
</dependency>
<!-- xml 解析 -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
@@ -175,7 +187,7 @@
<connection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</connection>
<developerConnection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</developerConnection>
<url>https://github.com/itfsw/mybatis-generator-plugin</url>
<tag>V1.0.8</tag>
<tag>V1.0.11</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -1,302 +0,0 @@
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.PluginConfiguration;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 批量插入插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/13 9:33
* ---------------------------------------------------------------------------
*/
@Deprecated
public class BatchInsertOldPlugin extends BasePlugin {
public static final String METHOD_BATCH_INSERT = "batchInsert"; // 方法名
private boolean hasModelBuilderPlugin; // 是否配置了ModelBuilderPlugin插件
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键
if ("com.mysql.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
&& "com.microsoft.jdbc.sqlserver.SQLServer".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
&& "com.microsoft.sqlserver.jdbc.SQLServerDriver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false){
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键!");
return false;
}
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件已过期,不再维护请使用com.itfsw.mybatis.generator.plugins.BatchInsertPlugin区分batchInsert和batchInsertSelective!");
return super.validate(warnings);
}
/**
* 初始化
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param introspectedTable
* @return
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
// 插件使用前提是使用了ModelColumnPlugin插件
Context ctx = getContext();
// 利用反射获取pluginConfigurations属性
try {
java.lang.reflect.Field field = Context.class.getDeclaredField("pluginConfigurations");
field.setAccessible(true);
List<PluginConfiguration> list = (List<PluginConfiguration>) field.get(ctx);
// 检查是否配置了ModelColumnPlugin插件
for (PluginConfiguration config: list) {
if (ModelColumnPlugin.class.getName().equals(config.getConfigurationType())){
this.hasModelBuilderPlugin = true;
}
}
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
}
}
/**
* Java Client Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param interfaze
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (hasModelBuilderPlugin){
// 方法生成
Method method = new Method(METHOD_BATCH_INSERT);
// 返回值类型
method.setReturnType(FullyQualifiedJavaType.getIntInstance());
// 添加参数
FullyQualifiedJavaType type = FullyQualifiedJavaType.getNewListInstance();
type.addTypeArgument(introspectedTable.getRules().calculateAllFieldsClass());
method.addParameter(new Parameter(type, "list", "@Param(\"list\")"));
FullyQualifiedJavaType type1 = new FullyQualifiedJavaType(introspectedTable.getRules().calculateAllFieldsClass().getShortName()+"."+ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(type1, "insertColumns", "@Param(\"insertColumns\")", true));
// 添加方法说明
commentGenerator.addGeneralMethodComment(method, introspectedTable);
// interface 增加方法
interfaze.addMethod(method);
logger.debug("itfsw(批量插入插件):" + interfaze.getType().getShortName() + "增加batchInsert方法。");
} else {
// 方法生成
Method method = new Method(METHOD_BATCH_INSERT);
// 方法可见性 interface会忽略
// method.setVisibility(JavaVisibility.PUBLIC);
// 返回值类型
method.setReturnType(FullyQualifiedJavaType.getIntInstance());
// 添加参数
FullyQualifiedJavaType type = FullyQualifiedJavaType.getNewListInstance();
type.addTypeArgument(introspectedTable.getRules().calculateAllFieldsClass());
method.addParameter(new Parameter(type, "list", "@Param(\"list\")"));
// 添加方法说明
commentGenerator.addGeneralMethodComment(method, introspectedTable);
// interface 增加方法
interfaze.addMethod(method);
logger.debug("itfsw(批量插入插件):" + interfaze.getType().getShortName() + "增加batchInsert方法。");
}
return true;
}
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param document
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
if (hasModelBuilderPlugin){
XmlElement element = new XmlElement("insert");
element.addAttribute(new Attribute("id", METHOD_BATCH_INSERT));
// 参数类型
element.addAttribute(new Attribute("parameterType", "map"));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(element);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(element, introspectedTable);
// choose 节点
XmlElement choose = new XmlElement("choose");
// when 节点
XmlElement when = new XmlElement("when");
when.addAttribute(new Attribute("test", "insertColumns.length != 0"));
when.addElement(new TextElement("insert into "+introspectedTable.getFullyQualifiedTableNameAtRuntime()+" ("));
XmlElement foreachInsertColumns = new XmlElement("foreach");
foreachInsertColumns.addAttribute(new Attribute("collection", "insertColumns"));
foreachInsertColumns.addAttribute(new Attribute("item", "column"));
foreachInsertColumns.addAttribute(new Attribute("separator", ","));
foreachInsertColumns.addElement(new TextElement("${column.value}"));
when.addElement(foreachInsertColumns);
when.addElement(new TextElement(")"));
// values
when.addElement(new TextElement("values"));
// foreach values
XmlElement foreachValues = new XmlElement("foreach");
foreachValues.addAttribute(new Attribute("collection", "list"));
foreachValues.addAttribute(new Attribute("item", "item"));
foreachValues.addAttribute(new Attribute("separator", ","));
foreachValues.addElement(new TextElement("("));
// foreach 所有插入的列,比较是否存在
XmlElement foreachInsertColumnsCheck = new XmlElement("foreach");
foreachInsertColumnsCheck.addAttribute(new Attribute("collection", "insertColumns"));
foreachInsertColumnsCheck.addAttribute(new Attribute("item", "column"));
foreachInsertColumnsCheck.addAttribute(new Attribute("separator", ","));
// 所有表字段
List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
for (int i = 0; i < columns.size(); i++) {
IntrospectedColumn introspectedColumn = columns.get(i);
XmlElement check = new XmlElement("if");
check.addAttribute(new Attribute("test", "'"+introspectedColumn.getActualColumnName()+"' == column.value"));
check.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "item.")));
foreachInsertColumnsCheck.addElement(check);
}
foreachValues.addElement(foreachInsertColumnsCheck);
foreachValues.addElement(new TextElement(")"));
when.addElement(foreachValues);
choose.addElement(when);
// 普通不带insertColumns参数实现
XmlElement otherwise = new XmlElement("otherwise");
this.addNormalBatchInsertXml(otherwise, introspectedTable);
choose.addElement(otherwise);
element.addElement(choose);
if (context.getPlugins().sqlMapInsertElementGenerated(element, introspectedTable)) {
document.getRootElement().addElement(element);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsert实现方法。");
}
} else {
XmlElement element = new XmlElement("insert"); //$NON-NLS-1$
element.addAttribute(new Attribute("id", METHOD_BATCH_INSERT)); //$NON-NLS-1$
// 参数类型
element.addAttribute(new Attribute("parameterType", FullyQualifiedJavaType.getNewListInstance().getFullyQualifiedName()));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(element);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(element, introspectedTable);
// 普通插入语句
this.addNormalBatchInsertXml(element, introspectedTable);
document.getRootElement().addElement(element);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsert实现方法。");
}
return true;
}
/**
* 普通不带insertColumns的插入语句Xml实现
*
* @param element
* @param introspectedTable
*/
private void addNormalBatchInsertXml(XmlElement element, IntrospectedTable introspectedTable) {
StringBuilder insertClause = new StringBuilder();
StringBuilder valuesClause = new StringBuilder();
insertClause.append("insert into "); //$NON-NLS-1$
insertClause.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
insertClause.append(" ("); //$NON-NLS-1$
valuesClause.append(" ("); //$NON-NLS-1$
List<String> valuesClauses = new ArrayList<String>();
List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
for (int i = 0; i < columns.size(); i++) {
IntrospectedColumn introspectedColumn = columns.get(i);
insertClause.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
// 生成foreach下插入values
valuesClause.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "item."));
if (i + 1 < columns.size()) {
insertClause.append(", "); //$NON-NLS-1$
valuesClause.append(", "); //$NON-NLS-1$
}
}
insertClause.append(')');
element.addElement(new TextElement(insertClause.toString()));
valuesClause.append(')');
valuesClauses.add(valuesClause.toString());
// 添加foreach节点
XmlElement foreachElement = new XmlElement("foreach");
foreachElement.addAttribute(new Attribute("collection", "list"));
foreachElement.addAttribute(new Attribute("item", "item"));
foreachElement.addAttribute(new Attribute("separator", ","));
for (String clause : valuesClauses) {
foreachElement.addElement(new TextElement(clause));
}
// values 构建
element.addElement(new TextElement("values"));
element.addElement(foreachElement);
}
}
@@ -65,9 +65,6 @@ public class BatchInsertPlugin extends BasePlugin {
return false;
}
// TODO
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件如之前使用1.0.5-的插件可继续使用com.itfsw.mybatis.generator.plugins.BatchInsertOldPlugin或者修改batchInsert(@Param(\"list\") List<Tb> list, @Param(\"insertColumns\") Tb.Column ... selective)调用为batchInsertSelective!");
return super.validate(warnings);
}
@@ -16,24 +16,27 @@
package com.itfsw.mybatis.generator.plugins;
import java.util.List;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import java.util.Properties;
/**
* ---------------------------------------------------------------------------
* 增加Criteria Builder方法
* 评论插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2016/12/28 14:56
* @time:2017/6/8 11:21
* ---------------------------------------------------------------------------
*/
@Deprecated
public class CriteriaBuilderPlugin extends ExampleEnhancedPlugin{
public class CommentPlugin extends BasePlugin {
public static final String PRE_TEMPLATE = "template"; // 模板 property
/**
* {@inheritDoc}
* 插件具体实现查看BasePlugin
* @param properties
*/
@Override
public boolean validate(List<String> warnings) {
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"插件已经过时,请使用com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin插件替换!");
return super.validate(warnings);
public void setProperties(Properties properties) {
super.setProperties(properties);
}
}
@@ -106,7 +106,6 @@ public class ExampleEnhancedPlugin extends BasePlugin {
// 添加接口CriteriaAdd
InnerInterface criteriaAddInterface = new InnerInterface("ICriteriaAdd");
criteriaAddInterface.setVisibility(JavaVisibility.PUBLIC);
commentGenerator.addInterfaceComment(criteriaAddInterface, introspectedTable);
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "增加接口ICriteriaAdd");
// ICriteriaAdd增加接口add
@@ -121,6 +120,8 @@ public class ExampleEnhancedPlugin extends BasePlugin {
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "." + criteriaAddInterface.getType().getShortName() + "增加方法add");
InnerClass innerClassWrapper = new InnerInterfaceWrapperToInnerClass(criteriaAddInterface);
// 添加注释
commentGenerator.addClassComment(innerClassWrapper, introspectedTable);
innerClass.addInnerClass(innerClassWrapper);
// 添加andIf方法
@@ -45,8 +45,36 @@ public class ModelBuilderPlugin extends BasePlugin {
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
List<Field> fields = topLevelClass.getFields();
// 判断是否有生成Model的WithBLOBs类
List<IntrospectedColumn> columns = introspectedTable.getRules().generateRecordWithBLOBsClass() ? introspectedTable.getNonBLOBColumns() : introspectedTable.getAllColumns();
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, columns);
topLevelClass.addInnerClass(innerClass);
return true;
}
/**
* Model Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getAllColumns());
topLevelClass.addInnerClass(innerClass);
return true;
}
/**
* 生成ModelBuilder
*
* @param topLevelClass
* @param introspectedTable
* @param columns
* @return
*/
private InnerClass generateModelBuilder(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, List<IntrospectedColumn> columns){
// 生成内部Builder类
InnerClass innerClass = new InnerClass(BUILDER_CLASS_NAME);
innerClass.setVisibility(JavaVisibility.PUBLIC);
@@ -68,8 +96,7 @@ public class ModelBuilderPlugin extends BasePlugin {
innerClass.addMethod(constructor);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + ".Builder增加的构造方法。");
for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
for (IntrospectedColumn introspectedColumn : columns) {
Field field = JavaBeansUtil.getJavaBeansField(introspectedColumn, context, introspectedTable);
Method setterMethod = JavaBeansUtil.getJavaBeansSetter(introspectedColumn, context, introspectedTable);
@@ -97,9 +124,9 @@ public class ModelBuilderPlugin extends BasePlugin {
build.addBodyLine("return this.obj;");
commentGenerator.addGeneralMethodComment(build, introspectedTable);
innerClass.addMethod(build);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + ".Builder增加build方法。");
topLevelClass.addInnerClass(innerClass);
return true;
return innerClass;
}
}
@@ -22,8 +22,6 @@ import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.JavaBeansUtil;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 数据Model属性对应Column获取插件
@@ -44,8 +42,31 @@ public class ModelColumnPlugin extends BasePlugin {
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
List<Field> fields = topLevelClass.getFields();
topLevelClass.addInnerEnum(this.generateColumnEnum(topLevelClass, introspectedTable));
return true;
}
/**
* Model Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
topLevelClass.addInnerEnum(this.generateColumnEnum(topLevelClass, introspectedTable));
return true;
}
/**
* 生成Column字段枚举
*
* @param topLevelClass
* @param introspectedTable
* @return
*/
private InnerEnum generateColumnEnum(TopLevelClass topLevelClass, IntrospectedTable introspectedTable){
// 生成内部枚举
InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(ENUM_NAME));
innerEnum.setVisibility(JavaVisibility.PUBLIC);
@@ -112,7 +133,6 @@ public class ModelColumnPlugin extends BasePlugin {
innerEnum.addMethod(asc);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加asc()和desc()方法。");
topLevelClass.addInnerEnum(innerEnum);
return true;
return innerEnum;
}
}
@@ -19,6 +19,7 @@ package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
@@ -26,6 +27,9 @@ import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.ArrayList;
import java.util.List;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
/**
@@ -38,11 +42,79 @@ import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
*/
public class SelectOneByExamplePlugin extends BasePlugin {
public static final String METHOD_SELECT_ONE_BY_EXAMPLE = "selectOneByExample"; // 方法名
public static final String METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS = "selectOneByExampleWithBLOBs"; // 方法名
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 有种情况下ModelBaseRecordClass不会生成不包含BLOBs的构造方法,造成selectOneByExample返回结果找不到对应的构造方法异常
if (introspectedTable.hasBLOBColumns() && !introspectedTable.getRules().generateRecordWithBLOBsClass()) {
// 添加没有BLOBs的构造方法
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setConstructor(true);
method.setName(topLevelClass.getType().getShortName());
commentGenerator.addGeneralMethodComment(method, introspectedTable);
// 使用没有blobs的字段
List<IntrospectedColumn> constructorColumns = introspectedTable.getNonBLOBColumns();
for (IntrospectedColumn introspectedColumn : constructorColumns) {
method.addParameter(new Parameter(introspectedColumn.getFullyQualifiedJavaType(), introspectedColumn.getJavaProperty()));
topLevelClass.addImportedType(introspectedColumn.getFullyQualifiedJavaType());
}
StringBuilder sb = new StringBuilder();
if (introspectedTable.getRules().generatePrimaryKeyClass()) {
boolean comma = false;
sb.append("super(");
for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
if (comma) {
sb.append(", ");
} else {
comma = true;
}
sb.append(introspectedColumn.getJavaProperty());
}
sb.append(");");
method.addBodyLine(sb.toString());
}
List<IntrospectedColumn> introspectedColumns;
if (!introspectedTable.getRules().generatePrimaryKeyClass() && introspectedTable.hasPrimaryKeyColumns()) {
introspectedColumns = introspectedTable.getNonBLOBColumns();
} else {
introspectedColumns = introspectedTable.getBaseColumns();
}
for (IntrospectedColumn introspectedColumn : introspectedColumns) {
sb.setLength(0);
sb.append("this.");
sb.append(introspectedColumn.getJavaProperty());
sb.append(" = ");
sb.append(introspectedColumn.getJavaProperty());
sb.append(';');
method.addBodyLine(sb.toString());
}
// 找到原有构造方法位置,保持构造方法放在一起美观
ArrayList<Method> methods = (ArrayList<Method>) topLevelClass.getMethods();
int index = 0;
for (Method m : methods) {
index++;
if (m.getName().equals(topLevelClass.getType().getShortName())) {
break;
}
}
methods.add(index, method);
}
return true;
}
/**
* Java Client Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param interfaze
* @param topLevelClass
* @param introspectedTable
@@ -50,34 +122,48 @@ public class SelectOneByExamplePlugin extends BasePlugin {
*/
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 方法生成
// 方法生成 selectOneByExample
Method method = JavaElementGeneratorTools.generateMethod(
METHOD_SELECT_ONE_BY_EXAMPLE,
JavaVisibility.DEFAULT,
introspectedTable.getRules().calculateAllFieldsClass(),
JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example")
);
commentGenerator.addGeneralMethodComment(method, introspectedTable);
commentGenerator.addGeneralMethodComment(method, introspectedTable);
// interface 增加方法
interfaze.addMethod(method);
logger.debug("itfsw(查询单条数据插件):"+interfaze.getType().getShortName()+"增加SelectOneByExample方法。");
logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExample方法。");
// 方法生成 selectOneByExampleWithBLOBs !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()) {
// 方法生成 selectOneByExample
Method method1 = JavaElementGeneratorTools.generateMethod(
METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS,
JavaVisibility.DEFAULT,
JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example")
);
commentGenerator.addGeneralMethodComment(method1, introspectedTable);
// interface 增加方法
interfaze.addMethod(method1);
logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExampleWithBLOBs方法。");
}
return true;
}
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param document
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
//数据库表名
String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();
// ------------------------------------ selectOneByExample ----------------------------------
// 生成查询语句
XmlElement selectOneElement = new XmlElement("select");
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
@@ -85,75 +171,86 @@ commentGenerator.addGeneralMethodComment(method, introspectedTable);
// 添加ID
selectOneElement.addAttribute(new Attribute("id", METHOD_SELECT_ONE_BY_EXAMPLE));
// 添加返回类型
selectOneElement.addAttribute(new Attribute("resultMap", introspectedTable.getBaseResultMapId()));
// 添加参数类型
selectOneElement.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType()));
selectOneElement.addElement(new TextElement("select"));
// ----------------------------------------- 表中是否有blob类型字段 ---------------------------------------
if (introspectedTable.hasBLOBColumns()){
// 添加返回类型
selectOneElement.addAttribute(new Attribute("resultMap", introspectedTable.getResultMapWithBLOBsId()));
// 添加参数类型
selectOneElement.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType()));
// 添加查询SQL
selectOneElement.addElement(new TextElement("select")); //$NON-NLS-1$
StringBuilder sb = new StringBuilder();
if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByExampleQueryId());
sb.append("' as QUERYID,"); //$NON-NLS-1$
selectOneElement.addElement(new TextElement(sb.toString()));
}
selectOneElement.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
selectOneElement.addElement(new TextElement(",")); //$NON-NLS-1$
selectOneElement.addElement(XmlElementGeneratorTools.getBlobColumnListElement(introspectedTable));
sb.setLength(0);
sb.append("from "); //$NON-NLS-1$
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
StringBuilder sb = new StringBuilder();
if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByExampleQueryId());
sb.append("' as QUERYID,");
selectOneElement.addElement(new TextElement(sb.toString()));
selectOneElement.addElement(XmlElementGeneratorTools.getExampleIncludeElement(introspectedTable));
XmlElement ifElement = new XmlElement("if"); //$NON-NLS-1$
ifElement.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-1$ //$NON-NLS-2$
ifElement.addElement(new TextElement("order by ${orderByClause}")); //$NON-NLS-1$
selectOneElement.addElement(ifElement);
// 只查询一条
selectOneElement.addElement(new TextElement("limit 1"));
} else {
// 添加返回类型
selectOneElement.addAttribute(new Attribute("resultMap", introspectedTable.getBaseResultMapId()));
// 添加参数类型
selectOneElement.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType()));
selectOneElement.addElement(new TextElement("select")); //$NON-NLS-1$
StringBuilder sb = new StringBuilder();
if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByExampleQueryId());
sb.append("' as QUERYID,"); //$NON-NLS-1$
selectOneElement.addElement(new TextElement(sb.toString()));
}
selectOneElement.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
sb.setLength(0);
sb.append("from "); //$NON-NLS-1$
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectOneElement.addElement(new TextElement(sb.toString()));
selectOneElement.addElement(XmlElementGeneratorTools.getExampleIncludeElement(introspectedTable));
XmlElement ifElement = new XmlElement("if"); //$NON-NLS-1$
ifElement.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-1$ //$NON-NLS-2$
ifElement.addElement(new TextElement("order by ${orderByClause}")); //$NON-NLS-1$
selectOneElement.addElement(ifElement);
// 只查询一条
selectOneElement.addElement(new TextElement("limit 1"));
}
selectOneElement.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
sb.setLength(0);
sb.append("from ");
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectOneElement.addElement(new TextElement(sb.toString()));
selectOneElement.addElement(XmlElementGeneratorTools.getExampleIncludeElement(introspectedTable));
XmlElement ifElement = new XmlElement("if");
ifElement.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-2$
ifElement.addElement(new TextElement("order by ${orderByClause}"));
selectOneElement.addElement(ifElement);
// 只查询一条
selectOneElement.addElement(new TextElement("limit 1"));
// 添加到根节点
document.getRootElement().addElement(selectOneElement);
logger.debug("itfsw(查询单条数据插件):"+introspectedTable.getMyBatis3XmlMapperFileName()+"增加SelectOneByExample方法("+(introspectedTable.hasBLOBColumns() ? "有" : "无")+"Blob类型))。");
logger.debug("itfsw(查询单条数据插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加selectOneByExample方法。");
// ------------------------------------ selectOneByExampleWithBLOBs ----------------------------------
// !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()) {
// 生成查询语句
XmlElement selectOneWithBLOBsElement = new XmlElement("select");
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(selectOneWithBLOBsElement);
// 添加ID
selectOneWithBLOBsElement.addAttribute(new Attribute("id", METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS));
// 添加返回类型
selectOneWithBLOBsElement.addAttribute(new Attribute("resultMap", introspectedTable.getResultMapWithBLOBsId()));
// 添加参数类型
selectOneWithBLOBsElement.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType()));
// 添加查询SQL
selectOneWithBLOBsElement.addElement(new TextElement("select"));
sb.setLength(0);
if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByExampleQueryId());
sb.append("' as QUERYID,");
selectOneWithBLOBsElement.addElement(new TextElement(sb.toString()));
}
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
selectOneWithBLOBsElement.addElement(new TextElement(","));
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getBlobColumnListElement(introspectedTable));
sb.setLength(0);
sb.append("from ");
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectOneWithBLOBsElement.addElement(new TextElement(sb.toString()));
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getExampleIncludeElement(introspectedTable));
XmlElement ifElement1 = new XmlElement("if");
ifElement1.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-2$
ifElement1.addElement(new TextElement("order by ${orderByClause}"));
selectOneWithBLOBsElement.addElement(ifElement1);
// 只查询一条
selectOneWithBLOBsElement.addElement(new TextElement("limit 1"));
// 添加到根节点
document.getRootElement().addElement(selectOneWithBLOBsElement);
logger.debug("itfsw(查询单条数据插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加selectOneByExampleWithBLOBs方法。");
}
return true;
}
@@ -169,14 +169,32 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
List<XmlElement> eles = this.findEle(xmlElement, "trim");
this.replaceEle(eles.get(0), "record.");
// upsertByExampleSelective的第二个trim比较特殊,需另行处理
this.replaceEleForUpsertByExampleSelective(eles.get(1), "record.", introspectedTable);
this.replaceEleForUpsertByExampleSelective(eles.get(1), "record.", introspectedTable, !introspectedTable.getRules().generateRecordWithBLOBsClass());
List<XmlElement> eles1 = this.findEle(xmlElement, "set");
for (XmlElement ele : eles1) {
this.replaceEle(ele, "record.");
}
}
// ====================================== 6. upsertSelectiveWithBLOBs ======================================
if ("upsertSelectiveWithBLOBs".equals(id)) {
List<XmlElement> eles = this.findEle(xmlElement, "trim");
for (XmlElement ele : eles) {
this.replaceEle(ele, "_parameter.");
}
}
// ====================================== 7. upsertByExampleSelectiveWithBLOBs ======================================
if ("upsertByExampleSelectiveWithBLOBs".equals(id)) {
List<XmlElement> eles = this.findEle(xmlElement, "trim");
this.replaceEle(eles.get(0), "record.");
// upsertByExampleSelective的第二个trim比较特殊,需另行处理
this.replaceEleForUpsertByExampleSelective(eles.get(1), "record.", introspectedTable, true);
List<XmlElement> eles1 = this.findEle(xmlElement, "set");
for (XmlElement ele : eles1) {
this.replaceEle(ele, "record.");
}
}
}
}
return true;
@@ -238,6 +256,10 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
}
XmlElement ifEle = new XmlElement("if");
// bug fixed: 修正使用autoDelimitKeywords过滤关键词造成的field前后加了特殊字符的问题
field = field.replaceAll("`", "").replaceAll("\"", "").replaceAll("'", "");
ifEle.addAttribute(new Attribute("test", prefix + "isSelective(\'" + field + "\')"));
ifEle.addElement(textElement);
whenEle.addElement(ifEle);
@@ -262,16 +284,17 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
* @param element
* @param prefix
* @param introspectedTable
* @param allColumns
*/
private void replaceEleForUpsertByExampleSelective(XmlElement element, String prefix, IntrospectedTable introspectedTable) {
private void replaceEleForUpsertByExampleSelective(XmlElement element, String prefix, IntrospectedTable introspectedTable, boolean allColumns) {
// choose
XmlElement chooseEle = new XmlElement("choose");
// when
XmlElement whenEle = new XmlElement("when");
whenEle.addAttribute(new Attribute("test", prefix + "isSelective()"));
for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
for (IntrospectedColumn introspectedColumn : (allColumns ? introspectedTable.getAllColumns() : introspectedTable.getNonBLOBColumns())) {
XmlElement eleIf = new XmlElement("if");
eleIf.addAttribute(new Attribute("test", prefix + "isSelective(\'" + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + "\')"));
eleIf.addAttribute(new Attribute("test", prefix + "isSelective(\'" + introspectedColumn.getActualColumnName() + "\')"));
eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
whenEle.addElement(eleIf);
@@ -0,0 +1,104 @@
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import org.mybatis.generator.api.IntrospectedTable;
/**
* ---------------------------------------------------------------------------
* table前缀,解决多数据源表重名问题插件(为Model、Mapper、Example、xml等增加前缀)
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/5/18 13:54
* ---------------------------------------------------------------------------
*/
public class TablePrefixPlugin extends BasePlugin {
public static final String PRE_PREFIX = "prefix"; // 前缀 property
private String prefix; // 前缀
/**
* 初始化阶段
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param introspectedTable
* @return
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
// 1. 首先获取全局配置
this.prefix = getProperties().getProperty(PRE_PREFIX);
// 2. 获取每个table 具体的
if (introspectedTable.getTableConfigurationProperty(PRE_PREFIX) != null){
this.prefix = introspectedTable.getTableConfigurationProperty(PRE_PREFIX);
}
// 3. 判断是否配置了前缀
if (this.prefix != null){
// 3.1. 为Model增加前缀
if (introspectedTable.getBaseRecordType() != null){
introspectedTable.setBaseRecordType(this.renameJavaType(introspectedTable.getBaseRecordType()));
}
// 3.2. 为ModelKey添加前缀
if (introspectedTable.getPrimaryKeyType() != null){
introspectedTable.setPrimaryKeyType(this.renameJavaType(introspectedTable.getPrimaryKeyType()));
}
// 3.3. WithBLOBs Model 添加前缀
if (introspectedTable.getRecordWithBLOBsType() != null){
introspectedTable.setRecordWithBLOBsType(this.renameJavaType(introspectedTable.getRecordWithBLOBsType()));
}
// 3.4. mapper 添加前缀
if (introspectedTable.getMyBatis3JavaMapperType() != null){
introspectedTable.setMyBatis3JavaMapperType(this.renameJavaType(introspectedTable.getMyBatis3JavaMapperType()));
}
// 3.5. example 添加前缀
if (introspectedTable.getExampleType() != null){
introspectedTable.setExampleType(this.renameJavaType(introspectedTable.getExampleType()));
}
// 3.6. Dao 添加前缀
if (introspectedTable.getDAOInterfaceType() != null){
introspectedTable.setDAOInterfaceType(this.renameJavaType(introspectedTable.getDAOInterfaceType()));
}
// 3.7. DAOImpl 添加前缀
if (introspectedTable.getDAOImplementationType() != null){
introspectedTable.setDAOImplementationType(this.renameJavaType(introspectedTable.getDAOImplementationType()));
}
// 3.8. 修正xml文件前缀
if (introspectedTable.getMyBatis3XmlMapperFileName() != null){
introspectedTable.setMyBatis3XmlMapperFileName(this.prefix + introspectedTable.getMyBatis3XmlMapperFileName());
}
}
}
/**
* 为类型添加前缀
*
* @param type
* @return
*/
private String renameJavaType(String type){
int lastDot = type.lastIndexOf(".") + 1;
return type.substring(0, lastDot) + this.prefix + type.substring(lastDot);
}
}
@@ -0,0 +1,184 @@
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import org.mybatis.generator.api.IntrospectedTable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ---------------------------------------------------------------------------
* table 重命名插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/6 15:18
* ---------------------------------------------------------------------------
*/
public class TableRenamePlugin extends BasePlugin {
public static final String PRE_SEARCH_STRING = "searchString"; // 查找 property
public static final String PRE_REPLACE_STRING = "replaceString"; // 替换 property
public static final String PRE_TABLE_OVERRIDE = "tableOverride"; // table 重命名 property
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 如果配置了searchString 或者 replaceString,二者不允许单独存在
if ((getProperties().getProperty(PRE_SEARCH_STRING) == null && getProperties().getProperty(PRE_REPLACE_STRING) != null)
|| (getProperties().getProperty(PRE_SEARCH_STRING) != null && getProperties().getProperty(PRE_REPLACE_STRING) == null)) {
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件的searchString、replaceString属性需配合使用,不能单独存在!");
return false;
}
return super.validate(warnings);
}
/**
* 初始化阶段
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param introspectedTable
* @return
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
// 1. 获取表单独配置
if (introspectedTable.getTableConfigurationProperty(PRE_TABLE_OVERRIDE) != null) {
String override = introspectedTable.getTableConfigurationProperty(PRE_TABLE_OVERRIDE);
// 3.1. Model修正名称
if (introspectedTable.getBaseRecordType() != null){
introspectedTable.setBaseRecordType(this.renameJavaType(introspectedTable.getBaseRecordType(), override, ""));
}
// 3.2. ModelKey修正名称
if (introspectedTable.getPrimaryKeyType() != null){
introspectedTable.setPrimaryKeyType(this.renameJavaType(introspectedTable.getPrimaryKeyType(), override, "Key"));
}
// 3.3. WithBLOBs Model 修正名称
if (introspectedTable.getRecordWithBLOBsType() != null){
introspectedTable.setRecordWithBLOBsType(this.renameJavaType(introspectedTable.getRecordWithBLOBsType(), override, "WithBLOBs"));
}
// 3.4. mapper 修正名称
if (introspectedTable.getMyBatis3JavaMapperType() != null){
introspectedTable.setMyBatis3JavaMapperType(this.renameJavaType(introspectedTable.getMyBatis3JavaMapperType(), override, "Mapper"));
}
// 3.5. example 修正名称
if (introspectedTable.getExampleType() != null){
introspectedTable.setExampleType(this.renameJavaType(introspectedTable.getExampleType(), override, "Example"));
}
// 3.6. Dao 添加前缀
if (introspectedTable.getDAOInterfaceType() != null){
introspectedTable.setDAOInterfaceType(this.renameJavaType(introspectedTable.getDAOInterfaceType(), override, "Dao"));
}
// 3.7. DAOImpl 添加前缀
if (introspectedTable.getDAOImplementationType() != null){
introspectedTable.setDAOImplementationType(this.renameJavaType(introspectedTable.getDAOImplementationType(), override, "DAOImpl"));
}
// 3.8. 修正xml文件名称
if (introspectedTable.getMyBatis3XmlMapperFileName() != null){
introspectedTable.setMyBatis3XmlMapperFileName(override + "Mapper.xml");
}
} else if (getProperties().getProperty(PRE_SEARCH_STRING) != null){
String searchString = getProperties().getProperty(PRE_SEARCH_STRING);
String replaceString = getProperties().getProperty(PRE_REPLACE_STRING);
// 3.1. Model修正名称
if (introspectedTable.getBaseRecordType() != null){
introspectedTable.setBaseRecordType(this.renameJavaType(introspectedTable.getBaseRecordType(), searchString, replaceString, ""));
}
// 3.2. ModelKey修正名称
if (introspectedTable.getPrimaryKeyType() != null){
introspectedTable.setPrimaryKeyType(this.renameJavaType(introspectedTable.getPrimaryKeyType(), searchString, replaceString, "Key"));
}
// 3.3. WithBLOBs Model 修正名称
if (introspectedTable.getRecordWithBLOBsType() != null){
introspectedTable.setRecordWithBLOBsType(this.renameJavaType(introspectedTable.getRecordWithBLOBsType(), searchString, replaceString, "WithBLOBs"));
}
// 3.4. mapper 修正名称
if (introspectedTable.getMyBatis3JavaMapperType() != null){
introspectedTable.setMyBatis3JavaMapperType(this.renameJavaType(introspectedTable.getMyBatis3JavaMapperType(), searchString, replaceString, "Mapper"));
}
// 3.5. example 修正名称
if (introspectedTable.getExampleType() != null){
introspectedTable.setExampleType(this.renameJavaType(introspectedTable.getExampleType(), searchString, replaceString, "Example"));
}
// 3.6. Dao 添加前缀
if (introspectedTable.getDAOInterfaceType() != null){
introspectedTable.setDAOInterfaceType(this.renameJavaType(introspectedTable.getDAOInterfaceType(), searchString, replaceString, "Dao"));
}
// 3.7. DAOImpl 添加前缀
if (introspectedTable.getDAOImplementationType() != null){
introspectedTable.setDAOImplementationType(this.renameJavaType(introspectedTable.getDAOImplementationType(), searchString, replaceString, "DAOImpl"));
}
// 3.8. 修正xml文件名称
if (introspectedTable.getMyBatis3XmlMapperFileName() != null){
Pattern pattern = Pattern.compile(searchString);
Matcher matcher = pattern.matcher(introspectedTable.getMyBatis3XmlMapperFileName());
String fileName = matcher.replaceAll(replaceString);
introspectedTable.setMyBatis3XmlMapperFileName(fileName);
}
}
}
/**
* 重命名类型
*
* @param type
* @param override
* @return
*/
private String renameJavaType(String type, String override, String suffix) {
int lastDot = type.lastIndexOf(".");
return type.substring(0, lastDot) + "." + override + suffix;
}
/**
* 重命名类型
*
* @param type
* @param searchString
* @param replaceString
* @return
*/
private String renameJavaType(String type, String searchString, String replaceString, String suffix) {
int lastDot = type.lastIndexOf(".");
String shortName = type.substring(lastDot + 1, type.length() - 1);
Pattern pattern = Pattern.compile(searchString);
Matcher matcher = pattern.matcher(shortName);
return type.substring(0, lastDot) + "." + matcher.replaceAll(replaceString) + suffix;
}
}
@@ -19,6 +19,7 @@ package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
@@ -45,6 +46,11 @@ public class UpsertPlugin extends BasePlugin {
public static final String METHOD_UPSERT_BY_EXAMPLE = "upsertByExample"; // 方法名
public static final String METHOD_UPSERT_BY_EXAMPLE_SELECTIVE = "upsertByExampleSelective"; // 方法名
public static final String METHOD_UPSERT_WITH_BLOBS = "upsertWithBLOBs"; // 方法名
public static final String METHOD_UPSERT_SELECTIVE_WITH_BLOBS = "upsertSelectiveWithBLOBs"; // 方法名
public static final String METHOD_UPSERT_BY_EXAMPLE_WITH_BLOBS = "upsertByExampleWithBLOBs"; // 方法名
public static final String METHOD_UPSERT_BY_EXAMPLE_SELECTIVE_WITH_BLOBS = "upsertByExampleSelectiveWithBLOBs"; // 方法名
public static final String PRE_ALLOW_MULTI_QUERIES = "allowMultiQueries"; // property allowMultiQueries
private boolean allowMultiQueries = false; // 是否允许多sql提交
@@ -88,7 +94,7 @@ public class UpsertPlugin extends BasePlugin {
METHOD_UPSERT,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record")
new Parameter(JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable), "record")
);
commentGenerator.addGeneralMethodComment(mUpsert, introspectedTable);
// interface 增加方法
@@ -100,7 +106,7 @@ public class UpsertPlugin extends BasePlugin {
METHOD_UPSERT_SELECTIVE,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record")
new Parameter(JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable), "record")
);
commentGenerator.addGeneralMethodComment(mUpsertSelective, introspectedTable);
// interface 增加方法
@@ -113,7 +119,7 @@ public class UpsertPlugin extends BasePlugin {
METHOD_UPSERT_BY_EXAMPLE,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record", "@Param(\"record\")"),
new Parameter(JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable), "record", "@Param(\"record\")"),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")")
);
commentGenerator.addGeneralMethodComment(mUpsertByExample, introspectedTable);
@@ -126,7 +132,7 @@ public class UpsertPlugin extends BasePlugin {
METHOD_UPSERT_BY_EXAMPLE_SELECTIVE,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record", "@Param(\"record\")"),
new Parameter(JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable), "record", "@Param(\"record\")"),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")")
);
commentGenerator.addGeneralMethodComment(mUpsertByExampleSelective, introspectedTable);
@@ -135,6 +141,61 @@ public class UpsertPlugin extends BasePlugin {
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExampleSelective方法。");
}
// !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()){
// ====================================== 1. upsertWithBLOBs ======================================
Method mUpsertWithBLOBs = JavaElementGeneratorTools.generateMethod(
METHOD_UPSERT_WITH_BLOBS,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable), "record")
);
commentGenerator.addGeneralMethodComment(mUpsertWithBLOBs, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsert方法。");
// ====================================== 2. upsertSelectiveWithBLOBs ======================================
Method mUpsertSelectiveWithBLOBs = JavaElementGeneratorTools.generateMethod(
METHOD_UPSERT_SELECTIVE_WITH_BLOBS,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable), "record")
);
commentGenerator.addGeneralMethodComment(mUpsertSelectiveWithBLOBs, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertSelectiveWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertSelective方法。");
if (this.allowMultiQueries){
// ====================================== 3. upsertByExampleWithBLOBs ======================================
Method mUpsertByExampleWithBLOBs = JavaElementGeneratorTools.generateMethod(
METHOD_UPSERT_BY_EXAMPLE_WITH_BLOBS,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable), "record", "@Param(\"record\")"),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")")
);
commentGenerator.addGeneralMethodComment(mUpsertByExampleWithBLOBs, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertByExampleWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExample方法。");
// ====================================== 4. upsertByExampleSelectiveWithBLOBs ======================================
Method mUpsertByExampleSelectiveWithBLOBs = JavaElementGeneratorTools.generateMethod(
METHOD_UPSERT_BY_EXAMPLE_SELECTIVE_WITH_BLOBS,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable), "record", "@Param(\"record\")"),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")")
);
commentGenerator.addGeneralMethodComment(mUpsertByExampleSelectiveWithBLOBs, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertByExampleSelectiveWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExampleSelective方法。");
}
}
return true;
}
@@ -149,6 +210,142 @@ public class UpsertPlugin extends BasePlugin {
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
this.generateXmlElementWithoutBLOBs(document, introspectedTable);
// !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()){
this.generateXmlElementWithBLOBs(document, introspectedTable);
}
return true;
}
/**
* 当Model有生成WithBLOBs类时的情况
*
* @param document
* @param introspectedTable
*/
private void generateXmlElementWithBLOBs(Document document, IntrospectedTable introspectedTable){
// ====================================== 1. upsert ======================================
XmlElement eleUpsertWithBLOBs = new XmlElement("insert");
eleUpsertWithBLOBs.addAttribute(new Attribute("id", METHOD_UPSERT_WITH_BLOBS));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(eleUpsertWithBLOBs);
// 参数类型
eleUpsertWithBLOBs.addAttribute(new Attribute("parameterType", JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable).getFullyQualifiedName()));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertWithBLOBs, introspectedTable);
// insert
eleUpsertWithBLOBs.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertWithBLOBs.addElement(XmlElementGeneratorTools.generateKeys(introspectedTable.getAllColumns()));
eleUpsertWithBLOBs.addElement(new TextElement("values"));
eleUpsertWithBLOBs.addElement(XmlElementGeneratorTools.generateValues(introspectedTable.getAllColumns()));
eleUpsertWithBLOBs.addElement(new TextElement("on duplicate key update "));
eleUpsertWithBLOBs.addElement(XmlElementGeneratorTools.generateSets(introspectedTable.getAllColumns()));
document.getRootElement().addElement(eleUpsertWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。");
// ====================================== 2. upsertSelective ======================================
XmlElement eleUpsertSelectiveWithBLOBs = new XmlElement("insert");
eleUpsertSelectiveWithBLOBs.addAttribute(new Attribute("id", METHOD_UPSERT_SELECTIVE_WITH_BLOBS));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(eleUpsertSelectiveWithBLOBs);
// 参数类型
eleUpsertSelectiveWithBLOBs.addAttribute(new Attribute("parameterType", JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable).getFullyQualifiedName()));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertSelectiveWithBLOBs, introspectedTable);
// insert
eleUpsertSelectiveWithBLOBs.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.generateKeysSelective(introspectedTable.getAllColumns()));
eleUpsertSelectiveWithBLOBs.addElement(new TextElement("values"));
eleUpsertSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.generateValuesSelective(introspectedTable.getAllColumns()));
eleUpsertSelectiveWithBLOBs.addElement(new TextElement("on duplicate key update "));
eleUpsertSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.generateSetsSelective(introspectedTable.getAllColumns(), null, false));
document.getRootElement().addElement(eleUpsertSelectiveWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
if (this.allowMultiQueries){
// ====================================== 2. upsertByExample ======================================
XmlElement eleUpsertByExampleWithBLOBs = new XmlElement("insert");
eleUpsertByExampleWithBLOBs.addAttribute(new Attribute("id", METHOD_UPSERT_BY_EXAMPLE_WITH_BLOBS));
// 参数类型
eleUpsertByExampleWithBLOBs.addAttribute(new Attribute("parameterType", "map"));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(eleUpsertByExampleWithBLOBs);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertByExampleWithBLOBs, introspectedTable, "record.");
// insert
eleUpsertByExampleWithBLOBs.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertByExampleWithBLOBs.addElement(XmlElementGeneratorTools.generateKeys(introspectedTable.getAllColumns()));
this.generateExistsClause(introspectedTable, eleUpsertByExampleWithBLOBs, false, true);
// multiQueries
eleUpsertByExampleWithBLOBs.addElement(new TextElement(";"));
// update
eleUpsertByExampleWithBLOBs.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
eleUpsertByExampleWithBLOBs.addElement(new TextElement("set"));
eleUpsertByExampleWithBLOBs.addElement(XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record."));
// update where
eleUpsertByExampleWithBLOBs.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
document.getRootElement().addElement(eleUpsertByExampleWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
// ====================================== 4. upsertByExampleSelective ======================================
XmlElement eleUpsertByExampleSelectiveWithBLOBs = new XmlElement("insert");
eleUpsertByExampleSelectiveWithBLOBs.addAttribute(new Attribute("id", METHOD_UPSERT_BY_EXAMPLE_SELECTIVE_WITH_BLOBS));
// 参数类型
eleUpsertByExampleSelectiveWithBLOBs.addAttribute(new Attribute("parameterType", "map"));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(eleUpsertByExampleSelectiveWithBLOBs);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertByExampleSelectiveWithBLOBs, introspectedTable, "record.");
// insert
eleUpsertByExampleSelectiveWithBLOBs.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertByExampleSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.generateKeysSelective(introspectedTable.getAllColumns(), "record."));
this.generateExistsClause(introspectedTable, eleUpsertByExampleSelectiveWithBLOBs, true, true);
// multiQueries
eleUpsertByExampleSelectiveWithBLOBs.addElement(new TextElement(";"));
// update
eleUpsertByExampleSelectiveWithBLOBs.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
eleUpsertByExampleSelectiveWithBLOBs.addElement(new TextElement("set"));
eleUpsertByExampleSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record."));
// update where
eleUpsertByExampleSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
document.getRootElement().addElement(eleUpsertByExampleSelectiveWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
}
}
/**
* 当Model没有生成WithBLOBs类时的情况
*
* @param document
* @param introspectedTable
*/
private void generateXmlElementWithoutBLOBs(Document document, IntrospectedTable introspectedTable){
// WithoutBLOBs也会存在只有一个时,不生成WithBLOBs对象的情况
boolean flag = !introspectedTable.getRules().generateRecordWithBLOBsClass();
List<IntrospectedColumn> columns = flag ? introspectedTable.getAllColumns() : introspectedTable.getNonBLOBColumns();
// ====================================== 1. upsert ======================================
XmlElement eleUpsert = new XmlElement("insert");
eleUpsert.addAttribute(new Attribute("id", METHOD_UPSERT));
@@ -156,18 +353,18 @@ public class UpsertPlugin extends BasePlugin {
commentGenerator.addComment(eleUpsert);
// 参数类型
eleUpsert.addAttribute(new Attribute("parameterType", introspectedTable.getRules().calculateAllFieldsClass().getFullyQualifiedName()));
eleUpsert.addAttribute(new Attribute("parameterType", JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable).getFullyQualifiedName()));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsert, introspectedTable);
// insert
eleUpsert.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsert.addElement(XmlElementGeneratorTools.generateKeys(introspectedTable.getAllColumns()));
eleUpsert.addElement(XmlElementGeneratorTools.generateKeys(columns));
eleUpsert.addElement(new TextElement("values"));
eleUpsert.addElement(XmlElementGeneratorTools.generateValues(introspectedTable.getAllColumns()));
eleUpsert.addElement(XmlElementGeneratorTools.generateValues(columns));
eleUpsert.addElement(new TextElement("on duplicate key update "));
eleUpsert.addElement(XmlElementGeneratorTools.generateSets(introspectedTable.getAllColumns()));
eleUpsert.addElement(XmlElementGeneratorTools.generateSets(columns));
document.getRootElement().addElement(eleUpsert);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。");
@@ -179,18 +376,18 @@ public class UpsertPlugin extends BasePlugin {
commentGenerator.addComment(eleUpsertSelective);
// 参数类型
eleUpsertSelective.addAttribute(new Attribute("parameterType", introspectedTable.getRules().calculateAllFieldsClass().getFullyQualifiedName()));
eleUpsertSelective.addAttribute(new Attribute("parameterType", JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable).getFullyQualifiedName()));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertSelective, introspectedTable);
// insert
eleUpsertSelective.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateKeysSelective(introspectedTable.getAllColumns()));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateKeysSelective(columns));
eleUpsertSelective.addElement(new TextElement("values"));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateValuesSelective(introspectedTable.getAllColumns()));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateValuesSelective(columns));
eleUpsertSelective.addElement(new TextElement("on duplicate key update "));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateSetsSelective(introspectedTable.getAllColumns(), null, false));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateSetsSelective(columns, null, false));
document.getRootElement().addElement(eleUpsertSelective);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
@@ -209,8 +406,8 @@ public class UpsertPlugin extends BasePlugin {
// insert
eleUpsertByExample.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertByExample.addElement(XmlElementGeneratorTools.generateKeys(introspectedTable.getAllColumns()));
this.generateExistsClause(introspectedTable, eleUpsertByExample, false);
eleUpsertByExample.addElement(XmlElementGeneratorTools.generateKeys(columns));
this.generateExistsClause(introspectedTable, eleUpsertByExample, false, flag);
// multiQueries
eleUpsertByExample.addElement(new TextElement(";"));
@@ -218,7 +415,7 @@ public class UpsertPlugin extends BasePlugin {
// update
eleUpsertByExample.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
eleUpsertByExample.addElement(new TextElement("set"));
eleUpsertByExample.addElement(XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record."));
eleUpsertByExample.addElement(XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record."));
// update where
eleUpsertByExample.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
@@ -238,8 +435,8 @@ public class UpsertPlugin extends BasePlugin {
// insert
eleUpsertByExampleSelective.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.generateKeysSelective(introspectedTable.getAllColumns(), "record."));
this.generateExistsClause(introspectedTable, eleUpsertByExampleSelective, true);
eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.generateKeysSelective(columns, "record."));
this.generateExistsClause(introspectedTable, eleUpsertByExampleSelective, true, flag);
// multiQueries
eleUpsertByExampleSelective.addElement(new TextElement(";"));
@@ -247,7 +444,7 @@ public class UpsertPlugin extends BasePlugin {
// update
eleUpsertByExampleSelective.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
eleUpsertByExampleSelective.addElement(new TextElement("set"));
eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record."));
eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record."));
// update where
eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
@@ -255,8 +452,6 @@ public class UpsertPlugin extends BasePlugin {
document.getRootElement().addElement(eleUpsertByExampleSelective);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
}
return true;
}
/**
@@ -265,13 +460,16 @@ public class UpsertPlugin extends BasePlugin {
* @param introspectedTable
* @param element
* @param selective
* @param allColumns
*/
private void generateExistsClause(IntrospectedTable introspectedTable, XmlElement element, boolean selective){
private void generateExistsClause(IntrospectedTable introspectedTable, XmlElement element, boolean selective, boolean allColumns){
List<IntrospectedColumn> columns = allColumns ? introspectedTable.getAllColumns() : introspectedTable.getNonBLOBColumns();
element.addElement(new TextElement("select"));
if (selective){
element.addElement(XmlElementGeneratorTools.generateValuesSelective(introspectedTable.getAllColumns(), "record.", false));
element.addElement(XmlElementGeneratorTools.generateValuesSelective(columns, "record.", false));
} else {
element.addElement(XmlElementGeneratorTools.generateValues(introspectedTable.getAllColumns(), "record.", false));
element.addElement(XmlElementGeneratorTools.generateValues(columns, "record.", false));
}
element.addElement(new TextElement("from dual where not exists"));
element.addElement(new TextElement("("));
@@ -16,12 +16,18 @@
package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.IWCommentGenerator;
import com.itfsw.mybatis.generator.plugins.CommentPlugin;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.TemplateCommentGenerator;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.PluginConfiguration;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.List;
/**
@@ -34,7 +40,48 @@ import java.util.List;
*/
public class BasePlugin extends PluginAdapter {
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class); // 日志
protected IWCommentGenerator commentGenerator = new IWCommentGenerator(); // 注释工具
protected CommentGenerator commentGenerator; // 注释工具
/**
* Set the context under which this plugin is running.
*
* @param context
* the new context
*/
@Override
public void setContext(Context context) {
super.setContext(context);
// 配置插件使用的模板引擎
PluginConfiguration cfg = PluginTools.getPluginConfiguration(CommentPlugin.class, context);
if (cfg == null || cfg.getProperty(CommentPlugin.PRE_TEMPLATE) == null){
if (context.getCommentGenerator() instanceof DefaultCommentGenerator){
// 使用默认模板引擎
commentGenerator = new TemplateCommentGenerator("default-comment.ftl", true);
} else {
// 用户自定义
commentGenerator = context.getCommentGenerator();
}
} else {
TemplateCommentGenerator templateCommentGenerator = new TemplateCommentGenerator(cfg.getProperty(CommentPlugin.PRE_TEMPLATE), false);
// ITFSW 插件使用的注释生成器
commentGenerator = templateCommentGenerator;
// 修正系统插件
try {
// 先执行一次生成CommentGenerator操作,然后再替换
context.getCommentGenerator();
Field field = Context.class.getDeclaredField("commentGenerator");
field.setAccessible(true);
field.set(context, templateCommentGenerator);
} catch (Exception e) {
logger.error("反射异常",e);
}
}
}
/**
* {@inheritDoc}
@@ -16,8 +16,11 @@
package com.itfsw.mybatis.generator.plugins.utils;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import static org.mybatis.generator.internal.util.messages.Messages.getString;
/**
* ---------------------------------------------------------------------------
* Java ele 生成工具
@@ -133,4 +136,39 @@ public class JavaElementGeneratorTools {
);
return generateMethodBody(method, "return this." + field.getName() + ";");
}
/**
* 获取Model没有BLOBs类时的类型
*
* @param introspectedTable
* @return
*/
public static FullyQualifiedJavaType getModelTypeWithoutBLOBs(IntrospectedTable introspectedTable){
FullyQualifiedJavaType type;
if (introspectedTable.getRules().generateBaseRecordClass()) {
type = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
} else if (introspectedTable.getRules().generatePrimaryKeyClass()) {
type = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType());
} else {
throw new RuntimeException(getString("RuntimeError.12"));
}
return type;
}
/**
* 获取Model有BLOBs类时的类型
*
* @param introspectedTable
* @return
*/
public static FullyQualifiedJavaType getModelTypeWithBLOBs(IntrospectedTable introspectedTable){
FullyQualifiedJavaType type;
if (introspectedTable.getRules().generateRecordWithBLOBsClass()) {
type = new FullyQualifiedJavaType(introspectedTable.getRecordWithBLOBsType());
} else {
// the blob fields must be rolled up into the base class
type = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
}
return type;
}
}
@@ -81,4 +81,19 @@ public class PluginTools {
}
return new ArrayList<>();
}
/**
* 获取插件配置
*
* @param plugin 插件
* @param ctx 上下文
* @return
*/
public static PluginConfiguration getPluginConfiguration(Class plugin, Context ctx){
int index = getPluginIndex(plugin, ctx);
if (index > -1){
return getConfigPlugins(ctx).get(index);
}
return null;
}
}
@@ -1,335 +0,0 @@
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins.utils.enhanced;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;
/**
* ---------------------------------------------------------------------------
* 注释生成工具
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/4/28 15:11
* ---------------------------------------------------------------------------
*/
public class IWCommentGenerator implements CommentGenerator {
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addJavaFileComment(org.mybatis.generator.api.dom.java.CompilationUnit)
*/
public void addJavaFileComment(CompilationUnit compilationUnit) {
// add no file level comments by default
}
/**
* Adds a suitable comment to warn users that the element was generated, and when it was generated.
* @param xmlElement the xml element
*/
public void addComment(XmlElement xmlElement) {
xmlElement.addElement(new TextElement("<!--"));
StringBuilder sb = new StringBuilder();
sb.append(" WARNING - ");
sb.append(MergeConstants.NEW_ELEMENT_TAG);
xmlElement.addElement(new TextElement(sb.toString()));
xmlElement.addElement(new TextElement(" This element is automatically generated by MyBatis Generator, do not modify."));
xmlElement.addElement(new TextElement(" @project https://github.com/itfsw/mybatis-generator-plugin"));
xmlElement.addElement(new TextElement("-->"));
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addRootComment(org.mybatis.generator.api.dom.xml.XmlElement)
*/
public void addRootComment(XmlElement rootElement) {
// add no document level comments by default
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addConfigurationProperties(java.util.Properties)
*/
public void addConfigurationProperties(Properties properties) {
}
/**
* This method adds the custom javadoc tag for. You may do nothing if you do not wish to include the Javadoc tag -
* however, if you do not include the Javadoc tag then the Java merge capability of the eclipse plugin will break.
* @param javaElement the java element
* @param markAsDoNotDelete the mark as do not delete
*/
protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
javaElement.addJavaDocLine(" *");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(MergeConstants.NEW_ELEMENT_TAG);
if (markAsDoNotDelete) {
sb.append(" do_not_delete_during_merge");
}
javaElement.addJavaDocLine(sb.toString());
javaElement.addJavaDocLine(" * @project https://github.com/itfsw/mybatis-generator-plugin");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addClassComment(org.mybatis.generator.api.dom.java.InnerClass, org.mybatis.generator.api.IntrospectedTable)
*/
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**");
innerClass.addJavaDocLine(" * This class was generated by MyBatis Generator.");
sb.append(" * This class corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString());
addJavadocTag(innerClass, false);
innerClass.addJavaDocLine(" */");
}
/**
* inner inter face 注释
*
* @param innerInterface
* @param introspectedTable
*/
public void addInterfaceComment(Interface innerInterface, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
innerInterface.addJavaDocLine("/**");
innerInterface.addJavaDocLine(" * This interface was generated by MyBatis Generator.");
sb.append(" * This interface corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerInterface.addJavaDocLine(sb.toString());
addJavadocTag(innerInterface, false);
innerInterface.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addTopLevelClassComment(org.mybatis.generator.api.dom.java.TopLevelClass, org.mybatis.generator.api.IntrospectedTable)
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
topLevelClass.addJavaDocLine("/**");
String remarks = introspectedTable.getRemarks();
if (StringUtility.stringHasValue(remarks)) {
topLevelClass.addJavaDocLine(" * Database Table Remarks:");
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for (String remarkLine : remarkLines) {
topLevelClass.addJavaDocLine(" * " + remarkLine);
}
}
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * This class was generated by MyBatis Generator.");
sb.append(" * This class corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(sb.toString());
addJavadocTag(topLevelClass, true);
topLevelClass.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addEnumComment(org.mybatis.generator.api.dom.java.InnerEnum, org.mybatis.generator.api.IntrospectedTable)
*/
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
innerEnum.addJavaDocLine("/**");
innerEnum.addJavaDocLine(" * This enum was generated by MyBatis Generator.");
sb.append(" * This enum corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerEnum.addJavaDocLine(sb.toString());
addJavadocTag(innerEnum, false);
innerEnum.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn)
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
field.addJavaDocLine("/**");
String remarks = introspectedColumn.getRemarks();
if (StringUtility.stringHasValue(remarks)) {
field.addJavaDocLine(" * Database Column Remarks:");
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for (String remarkLine : remarkLines) {
field.addJavaDocLine(" * " + remarkLine);
}
}
field.addJavaDocLine(" *");
field.addJavaDocLine(" * This field was generated by MyBatis Generator.");
StringBuilder sb = new StringBuilder();
sb.append(" * This field corresponds to the database column ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append('.');
sb.append(introspectedColumn.getActualColumnName());
field.addJavaDocLine(sb.toString());
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addFieldComment(org.mybatis.generator.api.dom.java.Field, org.mybatis.generator.api.IntrospectedTable)
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
field.addJavaDocLine(" * This field was generated by MyBatis Generator.");
sb.append(" * This field corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
field.addJavaDocLine(sb.toString());
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addGeneralMethodComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable)
*/
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**");
method.addJavaDocLine(" * This method was generated by MyBatis Generator.");
sb.append(" * This method corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
method.addJavaDocLine(sb.toString());
addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addGetterComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn)
*/
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**");
method.addJavaDocLine(" * This method was generated by MyBatis Generator.");
sb.append(" * This method returns the value of the database column ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append('.');
sb.append(introspectedColumn.getActualColumnName());
method.addJavaDocLine(sb.toString());
method.addJavaDocLine(" *");
sb.setLength(0);
sb.append(" * @return the value of ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append('.');
sb.append(introspectedColumn.getActualColumnName());
method.addJavaDocLine(sb.toString());
addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addSetterComment(org.mybatis.generator.api.dom.java.Method, org.mybatis.generator.api.IntrospectedTable, org.mybatis.generator.api.IntrospectedColumn)
*/
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**");
method.addJavaDocLine(" * This method was generated by MyBatis Generator.");
sb.append(" * This method sets the value of the database column ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append('.');
sb.append(introspectedColumn.getActualColumnName());
method.addJavaDocLine(sb.toString());
method.addJavaDocLine(" *");
Parameter parm = method.getParameters().get(0);
sb.setLength(0);
sb.append(" * @param ");
sb.append(parm.getName());
sb.append(" the value for ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append('.');
sb.append(introspectedColumn.getActualColumnName());
method.addJavaDocLine(sb.toString());
addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.CommentGenerator#addClassComment(org.mybatis.generator.api.dom.java.InnerClass, org.mybatis.generator.api.IntrospectedTable, boolean)
*/
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**");
innerClass.addJavaDocLine(" * This class was generated by MyBatis Generator.");
sb.append(" * This class corresponds to the database table ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString());
addJavadocTag(innerClass, markAsDoNotDelete);
innerClass.addJavaDocLine(" */");
}
}
@@ -56,4 +56,22 @@ public class InnerInterfaceWrapperToInnerClass extends InnerClass{
public String getFormattedContent(int indentLevel, CompilationUnit compilationUnit) {
return this.innerInterface.getFormattedContent(indentLevel, compilationUnit);
}
/**
* Getter method for property <tt>innerInterface</tt>.
* @return property value of innerInterface
* @author hewei
*/
public InnerInterface getInnerInterface() {
return innerInterface;
}
/**
* Setter method for property <tt>innerInterface</tt>.
* @param innerInterface value to be assigned to property innerInterface
* @author hewei
*/
public void setInnerInterface(InnerInterface innerInterface) {
this.innerInterface = innerInterface;
}
}
@@ -0,0 +1,504 @@
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins.utils.enhanced;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* ---------------------------------------------------------------------------
* 模板注释生成工具
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/8 13:21
* ---------------------------------------------------------------------------
*/
public class TemplateCommentGenerator implements CommentGenerator {
protected static final Logger logger = LoggerFactory.getLogger(TemplateCommentGenerator.class); // 日志
private Map<EnumNode, Template> templates = new HashMap<>(); // 模板
/**
* 构造函数
* @param templatePath 模板路径
* @param useForDefault 未使用Comment插件,用作默认注释生成器
*/
public TemplateCommentGenerator(String templatePath, boolean useForDefault) {
try {
Document doc = null;
if (useForDefault){
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath);
doc = new SAXReader().read(inputStream);
} else {
File file = new File(templatePath);
if (file.exists()) {
doc = new SAXReader().read(file);
} else {
logger.error("没有找到对应注释模板:" + templatePath);
}
}
// 遍历comment 节点
if (doc != null){
for (EnumNode node : EnumNode.values()){
Element element = doc.getRootElement().elementByID(node.value());
if (element != null){
Configuration cfg = new Configuration();
// 字符串清理
Template template = new Template(node.value(), element.getText(), cfg);
templates.put(node, template);
}
}
}
} catch (Exception e) {
logger.error("注释模板XML解析失败!", e);
}
}
/**
* 获取评论
* @param map 模板参数
* @param node 节点ID
* @return
*/
private String[] getComments(Map<String, Object> map, EnumNode node) {
// 1. 模板引擎解析
try {
StringWriter stringWriter = new StringWriter();
Template template = templates.get(node);
if (template != null){
template.process(map, stringWriter);
String comment = stringWriter.toString();
stringWriter.close();
// 需要先清理字符串
return comment.replaceFirst("^[\\s\\t\\r\\n]*", "").replaceFirst("[\\s\\t\\r\\n]*$", "").split("\n");
}
} catch (Exception e) {
logger.error("freemarker 解析失败!", e);
}
return null;
}
/**
* 添加评论
*
* @param javaElement
* @param map
* @param node
*/
private void addJavaElementComment(JavaElement javaElement, Map<String, Object> map, EnumNode node) {
// 获取评论
String[] comments = getComments(map, node);
if (comments != null){
// 去除空评论
if (comments.length == 1 && !StringUtility.stringHasValue(comments[0])){
return;
}
// 添加评论
for (String comment : comments){
javaElement.addJavaDocLine(comment);
}
}
}
/**
* 添加评论
*
* @param compilationUnit
* @param map
* @param node
*/
private void addCompilationUnitComment(CompilationUnit compilationUnit, Map<String, Object> map, EnumNode node) {
// 获取评论
String[] comments = getComments(map, node);
if (comments != null){
// 去除空评论
if (comments.length == 1 && !StringUtility.stringHasValue(comments[0])){
return;
}
// 添加评论
for (String comment : comments){
compilationUnit.addFileCommentLine(comment);
}
}
}
/**
* 添加评论
*
* @param xmlElement
* @param map
* @param node
*/
private void addXmlElementComment(XmlElement xmlElement, Map<String, Object> map, EnumNode node) {
// 获取评论
String[] comments = getComments(map, node);
if (comments != null){
// 去除空评论
if (comments.length == 1 && !StringUtility.stringHasValue(comments[0])){
return;
}
// 添加评论
for (String comment : comments){
xmlElement.addElement(new TextElement(comment));
}
}
}
/**
* Adds properties for this instance from any properties configured in the
* CommentGenerator configuration.
*
* This method will be called before any of the other methods.
*
* @param properties
* All properties from the configuration
*/
@Override
public void addConfigurationProperties(Properties properties) {
}
/**
* This method should add a Javadoc comment to the specified field. The field is related to the specified table and
* is used to hold the value of the specified column.
* <p>
*
* <b>Important:</b> This method should add a the nonstandard JavaDoc tag "@mbg.generated" to the comment. Without
* this tag, the Eclipse based Java merge feature will fail.
*
* @param field
* the field
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("field", field);
map.put("introspectedTable", introspectedTable);
map.put("introspectedColumn", introspectedColumn);
// 添加评论
addJavaElementComment(field, map, EnumNode.ADD_FIELD_COMMENT);
}
/**
* Adds the field comment.
*
* @param field
* the field
* @param introspectedTable
* the introspected table
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("field", field);
map.put("introspectedTable", introspectedTable);
// 添加评论
addJavaElementComment(field, map, EnumNode.ADD_FIELD_COMMENT);
}
/**
* Adds a comment for a model class. The Java code merger should
* be notified not to delete the entire class in case any manual
* changes have been made. So this method will always use the
* "do not delete" annotation.
*
* Because of difficulties with the Java file merger, the default implementation
* of this method should NOT add comments. Comments should only be added if
* specifically requested by the user (for example, by enabling table remark comments).
*
* @param topLevelClass
* the top level class
* @param introspectedTable
* the introspected table
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("topLevelClass", topLevelClass);
map.put("introspectedTable", introspectedTable);
// 添加评论
addJavaElementComment(topLevelClass, map, EnumNode.ADD_MODEL_CLASS_COMMENT);
}
/**
* Adds the inner class comment.
*
* @param innerClass
* the inner class
* @param introspectedTable
* the introspected table
*/
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
if (innerClass instanceof InnerInterfaceWrapperToInnerClass){
InnerInterface innerInterface = ((InnerInterfaceWrapperToInnerClass)innerClass).getInnerInterface();
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("innerInterface", innerInterface);
map.put("introspectedTable", introspectedTable);
// 添加评论
addJavaElementComment(innerInterface, map, EnumNode.ADD_INTERFACE_COMMENT);
} else {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("innerClass", innerClass);
map.put("introspectedTable", introspectedTable);
// 添加评论
addJavaElementComment(innerClass, map, EnumNode.ADD_CLASS_COMMENT);
}
}
/**
* Adds the inner class comment.
*
* @param innerClass
* the inner class
* @param introspectedTable
* the introspected table
* @param markAsDoNotDelete
* the mark as do not delete
*/
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("innerClass", innerClass);
map.put("introspectedTable", introspectedTable);
map.put("markAsDoNotDelete", markAsDoNotDelete);
// 添加评论
addJavaElementComment(innerClass, map, EnumNode.ADD_CLASS_COMMENT);
}
/**
* Adds the enum comment.
*
* @param innerEnum
* the inner enum
* @param introspectedTable
* the introspected table
*/
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("innerEnum", innerEnum);
map.put("introspectedTable", introspectedTable);
// 添加评论
addJavaElementComment(innerEnum, map, EnumNode.ADD_ENUM_COMMENT);
}
/**
* Adds the getter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("method", method);
map.put("introspectedTable", introspectedTable);
map.put("introspectedColumn", introspectedColumn);
// 添加评论
addJavaElementComment(method, map, EnumNode.ADD_GETTER_COMMENT);
}
/**
* Adds the setter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("method", method);
map.put("introspectedTable", introspectedTable);
map.put("introspectedColumn", introspectedColumn);
// 添加评论
addJavaElementComment(method, map, EnumNode.ADD_SETTER_COMMENT);
}
/**
* Adds the general method comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
*/
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("method", method);
map.put("introspectedTable", introspectedTable);
// 添加评论
addJavaElementComment(method, map, EnumNode.ADD_GENERAL_METHOD_COMMENT);
}
/**
* This method is called to add a file level comment to a generated java file. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the Java file merge function in Eclipse
* does not deal with this comment. If you run the generator repeatedly, you will only retain the comment from the
* initial run.
* <p>
*
* The default implementation does nothing.
*
* @param compilationUnit
* the compilation unit
*/
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("compilationUnit", compilationUnit);
// 添加评论
addCompilationUnitComment(compilationUnit, map, EnumNode.ADD_JAVA_FILE_COMMENT);
}
/**
* This method should add a suitable comment as a child element of the specified xmlElement to warn users that the
* element was generated and is subject to regeneration.
*
* @param xmlElement
* the xml element
*/
@Override
public void addComment(XmlElement xmlElement) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("xmlElement", xmlElement);
// 添加评论
addXmlElementComment(xmlElement, map, EnumNode.ADD_COMMENT);
}
/**
* This method is called to add a comment as the first child of the root element. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the XML file merge function does not deal
* with this comment. If you run the generator repeatedly, you will only retain the comment from the initial run.
* <p>
*
* The default implementation does nothing.
*
* @param rootElement
* the root element
*/
@Override
public void addRootComment(XmlElement rootElement) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("rootElement", rootElement);
// 添加评论
addXmlElementComment(rootElement, map, EnumNode.ADD_ROOT_COMMENT);
}
/**
* 评论模板节点ID
*/
public static enum EnumNode {
ADD_COMMENT("addComment"), // Xml 节点注释
ADD_ROOT_COMMENT("addRootComment"), // xml root 节点注释
ADD_JAVA_FILE_COMMENT("addJavaFileComment"), // java 文件注释
ADD_GENERAL_METHOD_COMMENT("addGeneralMethodComment"), // java 方法注释
ADD_SETTER_COMMENT("addSetterComment"), // setter 方法注释
ADD_GETTER_COMMENT("addGetterComment"), // getter 方式注释
ADD_ENUM_COMMENT("addEnumComment"), // 枚举 注释
ADD_CLASS_COMMENT("addClassComment"), // 类 注释
ADD_INTERFACE_COMMENT("addInterfaceComment"), // 接口 注释
ADD_MODEL_CLASS_COMMENT("addModelClassComment"), // model 类注释
ADD_FIELD_COMMENT("addFieldComment"), // 字段 注释
;
private final String value; // 值
/**
* 构造方法
* @param value
*/
EnumNode(String value) {
this.value = value;
}
/**
* 值
*
* @return
*/
public String value(){
return value;
}
}
}
+282
View File
@@ -0,0 +1,282 @@
<?xml version="1.0" encoding="UTF-8"?>
<template>
<!-- #############################################################################################################
/**
* This method is called to add a file level comment to a generated java file. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the Java file merge function in Eclipse
* does not deal with this comment. If you run the generator repeatedly, you will only retain the comment from the
* initial run.
* <p>
*
* The default implementation does nothing.
*
* @param compilationUnit
* the compilation unit
*/
-->
<comment ID="addJavaFileComment"></comment>
<!-- #############################################################################################################
/**
* This method should add a suitable comment as a child element of the specified xmlElement to warn users that the
* element was generated and is subject to regeneration.
*
* @param xmlElement
* the xml element
*/
-->
<comment ID="addComment"><![CDATA[
<!--
WARNING - ${mgb}
This element is automatically generated by MyBatis Generator, do not modify.
@project https://github.com/itfsw/mybatis-generator-plugin
-->
]]></comment>
<!-- #############################################################################################################
/**
* This method is called to add a comment as the first child of the root element. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the XML file merge function does not deal
* with this comment. If you run the generator repeatedly, you will only retain the comment from the initial run.
* <p>
*
* The default implementation does nothing.
*
* @param rootElement
* the root element
*/
-->
<comment ID="addRootComment"></comment>
<!-- #############################################################################################################
/**
* This method should add a Javadoc comment to the specified field. The field is related to the specified table and
* is used to hold the value of the specified column.
* <p>
*
* <b>Important:</b> This method should add a the nonstandard JavaDoc tag "@mbg.generated" to the comment. Without
* this tag, the Eclipse based Java merge feature will fail.
*
* @param field
* the field
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addFieldComment"><![CDATA[
<#if introspectedColumn??>
/**
<#if introspectedColumn.remarks?? && introspectedColumn.remarks != ''>
* Database Column Remarks:
<#list introspectedColumn.remarks?split("\n") as remark>
* ${remark}
</#list>
</#if>
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds a comment for a model class. The Java code merger should
* be notified not to delete the entire class in case any manual
* changes have been made. So this method will always use the
* "do not delete" annotation.
*
* Because of difficulties with the Java file merger, the default implementation
* of this method should NOT add comments. Comments should only be added if
* specifically requested by the user (for example, by enabling table remark comments).
*
* @param topLevelClass
* the top level class
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addModelClassComment"><![CDATA[
/**
<#if introspectedTable.remarks?? && introspectedTable.remarks != ''>
* Database Table Remarks:
<#list introspectedTable.remarks?split("\n") as remark>
* ${remark}
</#list>
</#if>
*
* This class was generated by MyBatis Generator.
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb} do_not_delete_during_merge
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the inner class comment.
*
* @param innerClass
* the inner class
* @param introspectedTable
* the introspected table
* @param markAsDoNotDelete
* the mark as do not delete
*/
-->
<comment ID="addClassComment"><![CDATA[
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}<#if markAsDoNotDelete?? && markAsDoNotDelete> do_not_delete_during_merge</#if>
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the enum comment.
*
* @param innerEnum
* the inner enum
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addEnumComment"><![CDATA[
/**
* This enum was generated by MyBatis Generator.
* This enum corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the interface comment.
*
* @param innerInterface
* the inner interface
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addInterfaceComment"><![CDATA[
/**
* This interface was generated by MyBatis Generator.
* This interface corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the getter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addGetterComment"><![CDATA[
<#if introspectedColumn??>
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* @return the value of ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the field ${method.name?replace("get","")?replace("is", "")?uncap_first}
*
* @return the value of field ${method.name?replace("get","")?replace("is", "")?uncap_first}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds the setter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addSetterComment"><![CDATA[
<#if introspectedColumn??>
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* @param ${method.parameters[0].name} the value for ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the field ${method.name?replace("set","")?uncap_first}
*
* @param ${method.parameters[0].name} the value for field ${method.name?replace("set","")?uncap_first}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds the general method comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addGeneralMethodComment"><![CDATA[
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
</template>