Compare commits

...
8 Commits
16 changed files with 466 additions and 97 deletions
+10 -3
View File
@@ -19,7 +19,7 @@
* [自定义注释插件(CommentPlugin)](#13-自定义注释插件)
* [增量插件(IncrementsPlugin)](#14-增量插件)
* [查询结果选择性返回插件(SelectSelectivePlugin)](#15-查询结果选择性返回插件)
* [官方ConstructorBased配置BUG临时修正插件(ConstructorBasedBugFixPlugin)](#16-官方ConstructorBased配置BUG临时修正插件)
* [官方ConstructorBased配置BUG临时修正插件(ConstructorBasedBugFixPlugin)](#16-官方constructorbased配置bug临时修正插件)
---------------------------------------
Maven引用:
@@ -27,7 +27,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.15</version>
<version>1.0.16</version>
</dependency>
```
---------------------------------------
@@ -206,6 +206,13 @@ public class Test {
.field3("xx")
.field4("xx")
.build();
// 或者使用builder静态方法创建Builder
Tb table = Tb.builder()
.field1("xx")
.field2("xx")
.field3("xx")
.field4("xx")
.build();
}
}
```
@@ -1061,4 +1068,4 @@ public class Test {
<!-- 官方ConstructorBased配置BUG临时修正插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ConstructorBasedBugFixPlugin" />
</xml>
```
```
+2 -2
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.15</version>
<version>1.0.16</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -212,7 +212,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.15</tag>
<tag>V1.0.16</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -16,10 +16,7 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.IncrementsPluginTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.*;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.TopLevelClass;
@@ -184,7 +181,7 @@ public class IncrementsPlugin extends BasePlugin {
TextElement textEle = (TextElement) textEles.get(0);
String[] strs = textEle.getContent().split("=");
String columnName = strs[0].trim();
IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName);
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
// 查找是否需要进行增量操作
if (incTools.supportColumn(introspectedColumn)) {
xmlElement.getElements().clear();
@@ -209,11 +206,11 @@ public class IncrementsPlugin extends BasePlugin {
// 找到text节点且格式为 set xx = xx 或者 xx = xx
if (ele instanceof TextElement) {
String text = ((TextElement) ele).getContent().trim();
if (text.matches("(set\\s)?\\S+\\s?=.*")) {
if (text.matches("(^set\\s)?\\S+\\s?=.*")) {
// 清理 set 操作
text = text.replaceFirst("set\\s", "").trim();
text = text.replaceFirst("^set\\s", "").trim();
String columnName = text.split("=")[0].trim();
IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName);
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
// 查找判断是否需要进行节点替换
if (incTools.supportColumn(introspectedColumn)) {
newEles.addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, text.endsWith(",")));
@@ -20,12 +20,15 @@ import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.FormatTools;
import com.itfsw.mybatis.generator.plugins.utils.IncrementsPluginTools;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.InnerTypeFullyQualifiedJavaType;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.JavaBeansUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ---------------------------------------------------------------------------
@@ -37,6 +40,7 @@ import java.util.List;
*/
public class ModelBuilderPlugin extends BasePlugin {
public static final String BUILDER_CLASS_NAME = "Builder"; // Builder 类名
private Map<IntrospectedTable, InnerTypeFullyQualifiedJavaType> innerClasses = new HashMap<>();
/**
* Model Methods 生成
@@ -49,7 +53,7 @@ public class ModelBuilderPlugin extends BasePlugin {
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 判断是否有生成Model的WithBLOBs类
List<IntrospectedColumn> columns = introspectedTable.getRules().generateRecordWithBLOBsClass() ? introspectedTable.getNonBLOBColumns() : introspectedTable.getAllColumns();
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, columns, true);
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, columns);
topLevelClass.addInnerClass(innerClass);
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
@@ -63,7 +67,7 @@ public class ModelBuilderPlugin extends BasePlugin {
*/
@Override
public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getAllColumns(), false);
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getAllColumns());
topLevelClass.addInnerClass(innerClass);
return super.modelRecordWithBLOBsClassGenerated(topLevelClass, introspectedTable);
}
@@ -76,7 +80,7 @@ public class ModelBuilderPlugin extends BasePlugin {
*/
@Override
public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getPrimaryKeyColumns(), false);
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getPrimaryKeyColumns());
topLevelClass.addInnerClass(innerClass);
return super.modelPrimaryKeyClassGenerated(topLevelClass, introspectedTable);
}
@@ -86,14 +90,34 @@ public class ModelBuilderPlugin extends BasePlugin {
* @param topLevelClass
* @param introspectedTable
* @param columns
* @param modelBaseRecord
* @return
*/
private InnerClass generateModelBuilder(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, List<IntrospectedColumn> columns, boolean modelBaseRecord) {
private InnerClass generateModelBuilder(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, List<IntrospectedColumn> columns) {
// 生成内部Builder类
InnerClass innerClass = new InnerClass(BUILDER_CLASS_NAME);
innerClass.setVisibility(JavaVisibility.PUBLIC);
innerClass.setStatic(true);
// 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
// 顺序为 key base withBLOBs
InnerTypeFullyQualifiedJavaType builderType = new InnerTypeFullyQualifiedJavaType(topLevelClass.getType().getFullyQualifiedName() + "." + BUILDER_CLASS_NAME);
if (innerClasses.get(introspectedTable) != null) {
innerClass.setSuperClass(innerClasses.get(introspectedTable));
innerClasses.remove(introspectedTable);
}
innerClasses.put(introspectedTable, builderType);
// 增加静态builder方法实现和lombok一样
Method builder = JavaElementGeneratorTools.generateMethod(
"builder",
JavaVisibility.PUBLIC,
builderType
);
commentGenerator.addGeneralMethodComment(builder, introspectedTable);
builder.setStatic(true);
builder.addBodyLine("return new " + builderType.getShortName() + "();");
topLevelClass.addMethod(builder);
commentGenerator.addClassComment(innerClass, introspectedTable);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + "增加内部Builder类。");
@@ -146,62 +170,60 @@ public class ModelBuilderPlugin extends BasePlugin {
// ========================================== IncrementsPlugin =======================================
IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
if (incTools.support()) {
if (modelBaseRecord) {
// 增加枚举
InnerEnum eIncrements = new InnerEnum(new FullyQualifiedJavaType("Inc"));
eIncrements.setVisibility(JavaVisibility.PUBLIC);
eIncrements.setStatic(true);
eIncrements.addEnumConstant("INC(\"+\")");
eIncrements.addEnumConstant("DEC(\"-\")");
commentGenerator.addEnumComment(eIncrements, introspectedTable);
// 生成属性和构造函数
Field fValue = new Field("value", FullyQualifiedJavaType.getStringInstance());
fValue.setVisibility(JavaVisibility.PRIVATE);
fValue.setFinal(true);
commentGenerator.addFieldComment(fValue, introspectedTable);
eIncrements.addField(fValue);
// 增加枚举
InnerEnum eIncrements = new InnerEnum(new FullyQualifiedJavaType("Inc"));
eIncrements.setVisibility(JavaVisibility.PUBLIC);
eIncrements.setStatic(true);
eIncrements.addEnumConstant("INC(\"+\")");
eIncrements.addEnumConstant("DEC(\"-\")");
commentGenerator.addEnumComment(eIncrements, introspectedTable);
// 生成属性和构造函数
Field fValue = new Field("value", FullyQualifiedJavaType.getStringInstance());
fValue.setVisibility(JavaVisibility.PRIVATE);
fValue.setFinal(true);
commentGenerator.addFieldComment(fValue, introspectedTable);
eIncrements.addField(fValue);
Method mInc = new Method("Inc");
mInc.setConstructor(true);
mInc.addBodyLine("this.value = value;");
mInc.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "value"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
eIncrements.addMethod(mInc);
Method mInc = new Method("Inc");
mInc.setConstructor(true);
mInc.addBodyLine("this.value = value;");
mInc.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "value"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
eIncrements.addMethod(mInc);
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
eIncrements.addMethod(mValue);
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
eIncrements.addMethod(mValue);
innerClass.addInnerEnum(eIncrements);
// 增加field
Field fIncrements = JavaElementGeneratorTools.generateField(
IncrementsPlugin.FIELD_INC_MAP,
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("Map<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">"),
"new HashMap<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">()"
);
commentGenerator.addFieldComment(fIncrements, introspectedTable);
topLevelClass.addField(fIncrements);
topLevelClass.addImportedType("java.util.Map");
topLevelClass.addImportedType("java.util.HashMap");
// getter&setter
Method mGetter = JavaElementGeneratorTools.generateGetterMethod(fIncrements);
commentGenerator.addGetterComment(mGetter, introspectedTable, null);
topLevelClass.addMethod(mGetter);
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
topLevelClass.addMethod(mSetter);
// 增加判断方法
Method mHasIncsForColumn = JavaElementGeneratorTools.generateMethod(
IncrementsPlugin.METHOD_INC_CHECK,
JavaVisibility.PUBLIC,
FullyQualifiedJavaType.getBooleanPrimitiveInstance(),
new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")
);
commentGenerator.addGeneralMethodComment(mHasIncsForColumn, introspectedTable);
mHasIncsForColumn.addBodyLine("return " + IncrementsPlugin.FIELD_INC_MAP + ".get(column) != null;");
FormatTools.addMethodWithBestPosition(topLevelClass, mHasIncsForColumn);
}
innerClass.addInnerEnum(eIncrements);
// 增加field
Field fIncrements = JavaElementGeneratorTools.generateField(
IncrementsPlugin.FIELD_INC_MAP,
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("Map<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">"),
"new HashMap<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">()"
);
commentGenerator.addFieldComment(fIncrements, introspectedTable);
topLevelClass.addField(fIncrements);
topLevelClass.addImportedType("java.util.Map");
topLevelClass.addImportedType("java.util.HashMap");
// getter&setter
Method mGetter = JavaElementGeneratorTools.generateGetterMethod(fIncrements);
commentGenerator.addGetterComment(mGetter, introspectedTable, null);
topLevelClass.addMethod(mGetter);
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
topLevelClass.addMethod(mSetter);
// 增加判断方法
Method mHasIncsForColumn = JavaElementGeneratorTools.generateMethod(
IncrementsPlugin.METHOD_INC_CHECK,
JavaVisibility.PUBLIC,
FullyQualifiedJavaType.getBooleanPrimitiveInstance(),
new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")
);
commentGenerator.addGeneralMethodComment(mHasIncsForColumn, introspectedTable);
mHasIncsForColumn.addBodyLine("return " + IncrementsPlugin.FIELD_INC_MAP + ".get(column) != null;");
FormatTools.addMethodWithBestPosition(topLevelClass, mHasIncsForColumn);
// Builder 中 添加字段支持
for (IntrospectedColumn column : columns) {
@@ -17,6 +17,7 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.IntrospectedTableTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import org.mybatis.generator.api.IntrospectedColumn;
@@ -33,6 +34,7 @@ import java.util.regex.Pattern;
* ---------------------------------------------------------------------------
* Selective 增强插件
* ---------------------------------------------------------------------------
*
* @author: hewei
* @time:2017/4/20 15:39
* ---------------------------------------------------------------------------
@@ -60,6 +62,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
/**
* Model Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param topLevelClass
* @param introspectedTable
* @return
@@ -115,6 +118,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param document
* @param introspectedTable
* @return
@@ -181,6 +185,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
/**
* 替换节点if信息
*
* @param element
* @param prefix
* @param introspectedTable
@@ -193,7 +198,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
whenEle.addAttribute(new Attribute("test", prefix + "isSelective()"));
for (Element ele : element.getElements()) {
// 对于字符串主键,是没有if判断节点的
if (ele instanceof XmlElement){
if (ele instanceof XmlElement) {
// if的text节点
XmlElement xmlElement = (XmlElement) ele;
@@ -204,7 +209,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
if (text.matches("#\\{.*\\},?")) {
Pattern pattern = Pattern.compile("#\\{(.*?),.*\\},?");
Matcher matcher = pattern.matcher(text);
if (matcher.find()){
if (matcher.find()) {
String field = matcher.group(1);
// 查找对应column
for (IntrospectedColumn column : introspectedTable.getAllColumns()) {
@@ -214,19 +219,21 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
}
}
} else {
if (text.matches(".*=.*")){
if (text.matches(".*=.*")) {
columnName = text.split("=")[0];
} else {
columnName = text.replaceAll(",", "");
}
// bug fixed: 修正使用autoDelimitKeywords过滤关键词造成的field前后加了特殊字符的问题
columnName = columnName.trim().replaceAll("`", "").replaceAll("\"", "").replaceAll("'", "");
// columnName = columnName.trim().replaceAll("`", "").replaceAll("\"", "").replaceAll("'", "");
}
IntrospectedColumn column = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
XmlElement ifEle = new XmlElement("if");
ifEle.addAttribute(new Attribute("test", prefix + "isSelective(\'" + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedTable.getColumn(columnName)) + "\')"));
for (Element ifChild : xmlElement.getElements()){
ifEle.addAttribute(new Attribute("test", prefix + "isSelective(\'" + column.getActualColumnName() + "\')"));
for (Element ifChild : xmlElement.getElements()) {
ifEle.addElement(ifChild);
}
whenEle.addElement(ifEle);
@@ -251,6 +258,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
/**
* 替换节点upsertByExampleSelective if信息
*
* @param element
* @param prefix
* @param introspectedTable
@@ -16,10 +16,7 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.IncrementsPluginTools;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.*;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
@@ -438,8 +435,8 @@ public class UpsertPlugin extends BasePlugin {
// 获取if节点
for (Element element : trimXmlElement.getElements()) {
String text = ((TextElement) (((XmlElement) element).getElements().get(0))).getContent();
String columnName = text.split("=")[0].trim().replaceAll("`", "").replaceAll("\"", "").replaceAll("'", "");
IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName);
String columnName = text.split("=")[0];
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
if (incTools.supportColumn(introspectedColumn)) {
// if 节点数据替换
((XmlElement) element).getElements().clear();
@@ -465,8 +462,8 @@ public class UpsertPlugin extends BasePlugin {
if (incTools.support()) {
// 获取column
String text = element.getContent().trim();
String columnName = text.split("=")[0].trim().replaceAll("`", "").replaceAll("\"", "").replaceAll("'", "");
IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName);
String columnName = text.split("=")[0];
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
if (incTools.supportColumn(introspectedColumn)) {
xmlElement.getElements().addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, text.endsWith(",")));
continue;
@@ -74,7 +74,7 @@ public class IncrementsPluginTools {
// 切分
String[] incrementsColumnsStrs = incrementsColumns.split(",");
for (String incrementsColumnsStr : incrementsColumnsStrs) {
IntrospectedColumn column = introspectedTable.getColumn(incrementsColumnsStr.trim());
IntrospectedColumn column = IntrospectedTableTools.safeGetColumn(introspectedTable, incrementsColumnsStr);
if (column == null) {
warnings.add("itfsw:插件" + IncrementsPlugin.class.getTypeName() + "插件没有找到column为" + incrementsColumnsStr.trim() + "的字段!");
} else {
@@ -146,12 +146,12 @@ public class IncrementsPluginTools {
when.addAttribute(new Attribute(
"test",
(hasPrefix ? "record." : "_parameter.") + IncrementsPlugin.METHOD_INC_CHECK
+ "('" + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + "')"
+ "('" + MyBatis3FormattingUtilities.escapeStringForMyBatis3(introspectedColumn.getActualColumnName()) + "')"
));
TextElement spec = new TextElement(
MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)
+ " ${" + (hasPrefix ? "record." : "")
+ IncrementsPlugin.FIELD_INC_MAP + "." + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ".value} "
+ IncrementsPlugin.FIELD_INC_MAP + "." + MyBatis3FormattingUtilities.escapeStringForMyBatis3(introspectedColumn.getActualColumnName()) + ".value} "
+ MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null));
when.addElement(spec);
choose.addElement(when);
@@ -18,10 +18,12 @@ package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin;
import org.mybatis.generator.api.FullyQualifiedTable;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.JavaModelGeneratorConfiguration;
import org.mybatis.generator.config.PluginConfiguration;
import org.mybatis.generator.internal.util.StringUtility;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
@@ -31,6 +33,7 @@ import java.lang.reflect.Method;
* ---------------------------------------------------------------------------
* IntrospectedTable 的一些拓展增强
* ---------------------------------------------------------------------------
*
* @author: hewei
* @time:2017/6/13 13:48
* ---------------------------------------------------------------------------
@@ -68,7 +71,7 @@ public class IntrospectedTableTools {
// 注意!! 如果配置了ExampleTargetPlugin插件,要修正Example 位置
PluginConfiguration configuration = PluginTools.getPluginConfiguration(context, ExampleTargetPlugin.class);
if (configuration != null && configuration.getProperty(ExampleTargetPlugin.TARGET_PACKAGE_KEY) != null){
if (configuration != null && configuration.getProperty(ExampleTargetPlugin.TARGET_PACKAGE_KEY) != null) {
String exampleType = introspectedTable.getExampleType();
// 修改包名
JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = context.getJavaModelGeneratorConfiguration();
@@ -78,4 +81,27 @@ public class IntrospectedTableTools {
introspectedTable.setExampleType(newExampleType);
}
}
/**
* 安全获取column 通过正则获取的name可能包含beginningDelimiter&&endingDelimiter
*
* @param introspectedTable
* @param columnName
* @return
*/
public static IntrospectedColumn safeGetColumn(IntrospectedTable introspectedTable, String columnName) {
// columnName
columnName = columnName.trim();
// 过滤
String beginningDelimiter = introspectedTable.getContext().getBeginningDelimiter();
if (StringUtility.stringHasValue(beginningDelimiter)) {
columnName = columnName.replaceFirst("^" + beginningDelimiter, "");
}
String endingDelimiter = introspectedTable.getContext().getEndingDelimiter();
if (StringUtility.stringHasValue(endingDelimiter)) {
columnName = columnName.replaceFirst(endingDelimiter + "$", "");
}
return introspectedTable.getColumn(columnName);
}
}
@@ -120,7 +120,7 @@ public class XmlElementGeneratorTools {
public static void useGeneratedKeys(XmlElement element, IntrospectedTable introspectedTable, String prefix) {
GeneratedKey gk = introspectedTable.getGeneratedKey();
if (gk != null) {
IntrospectedColumn introspectedColumn = introspectedTable.getColumn(gk.getColumn());
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, gk.getColumn());
// if the column is null, then it's a configuration error. The
// warning has already been reported
if (introspectedColumn != null) {
@@ -0,0 +1,76 @@
/*
* 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.dom.java.FullyQualifiedJavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/8/2 16:55
* ---------------------------------------------------------------------------
*/
public class InnerTypeFullyQualifiedJavaType extends FullyQualifiedJavaType {
private final static Logger logger = LoggerFactory.getLogger(InnerTypeFullyQualifiedJavaType.class);
private String outerType; // 内部类
/**
* Use this constructor to construct a generic type with the specified type parameters.
* @param fullTypeSpecification the full type specification
*/
public InnerTypeFullyQualifiedJavaType(String fullTypeSpecification){
super(fullTypeSpecification);
try{
// 修正package
java.lang.reflect.Field packageName = this.getClass().getSuperclass().getDeclaredField("packageName");
packageName.setAccessible(true);
String oldPackageName = getPackageName();
packageName.set(this, oldPackageName.substring(0, oldPackageName.lastIndexOf(".")));
outerType = oldPackageName.substring(oldPackageName.lastIndexOf(".") + 1);
} catch (Exception e){
logger.error("InnerTypeFullyQualifiedJavaType 赋值失败!", e);
}
}
/**
* This method returns the fully qualified name - including any generic type parameters.
*
* @return Returns the fullyQualifiedName.
*/
@Override
public String getFullyQualifiedName() {
String fullyQualifiedName = super.getFullyQualifiedName();
String before = fullyQualifiedName.substring(0, fullyQualifiedName.lastIndexOf("."));
String end = fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf("."));
return before + "." + outerType + end;
}
/**
* Gets the short name.
*
* @return Returns the shortName - including any type arguments.
*/
@Override
public String getShortName() {
return outerType + "." + super.getShortName();
}
}
@@ -21,9 +21,14 @@ import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
@@ -66,7 +71,7 @@ public class IncrementsPluginTest {
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试生成的方法
ObjectUtil tbBuilder = new ObjectUtil(loader, packagz + ".Tb$Builder");
List<Method> methods = tbBuilder.getMethods("incF1");
List<Method> methods = getDeclaredMethods(tbBuilder.getCls(), "incF1");
Assert.assertEquals(methods.size(), 2);
// 自增方法
Method incMethod = methods.get(0).getParameterTypes().length == 1 ? methods.get(1) : methods.get(0);
@@ -74,19 +79,36 @@ public class IncrementsPluginTest {
// 2. 测试有空格
ObjectUtil tbKeysBuilder = new ObjectUtil(loader, packagz + ".TbKeys$Builder");
Assert.assertEquals(tbKeysBuilder.getMethods("incF1").size(), 2);
Assert.assertEquals(tbKeysBuilder.getMethods("incF2").size(), 2);
Assert.assertEquals(tbKeysBuilder.getMethods("incF3").size(), 2);
Assert.assertEquals(getDeclaredMethods(tbKeysBuilder.getCls(), "incF1").size(), 2);
Assert.assertEquals(getDeclaredMethods(tbKeysBuilder.getCls(), "incF2").size(), 2);
Assert.assertEquals(getDeclaredMethods(tbKeysBuilder.getCls(), "incF3").size(), 2);
// 3. 测试在WithBlobs正确生成
ObjectUtil tbBlobsWithBLOBs = new ObjectUtil(loader, packagz + ".TbBlobsWithBLOBs$Builder");
Assert.assertEquals(tbBlobsWithBLOBs.getMethods("incF1").size(), 2);
Assert.assertEquals(tbBlobsWithBLOBs.getMethods("incF2").size(), 1);
Assert.assertEquals(tbBlobsWithBLOBs.getMethods("incF3").size(), 2);
Assert.assertEquals(getDeclaredMethods(tbBlobsWithBLOBs.getCls(), "incF1").size(), 2);
Assert.assertEquals(getDeclaredMethods(tbBlobsWithBLOBs.getCls(), "incF2").size(), 1);
Assert.assertEquals(getDeclaredMethods(tbBlobsWithBLOBs.getCls(), "incF3").size(), 2);
}
});
}
/**
* 获取类方法
* @param cls
* @param name
* @return
*/
private List<Method> getDeclaredMethods(Class cls, String name) {
List<Method> list = new ArrayList<>();
Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(name) && cls.equals(method.getReturnType())) {
list.add(method);
}
}
return list;
}
/**
* 测试生成的sql和具体执行
*/
@@ -188,4 +210,36 @@ public class IncrementsPluginTest {
}
});
}
/**
* 测试 autoDelimitKeywords
*/
@Test
public void testWithAutoDelimitKeywords() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-autoDelimitKeywords.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试updateByExample、updateByExampleSelective
ObjectUtil TbKeyWord = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbKeyWordMapper")));
ObjectUtil TbKeyWordExample = new ObjectUtil(loader, packagz + ".TbKeyWordExample");
ObjectUtil criteria = new ObjectUtil(TbKeyWordExample.invoke("createCriteria"));
criteria.invoke("andIdEqualTo", 1l);
ObjectUtil TbKeyWordBuilder = new ObjectUtil(loader, packagz + ".TbKeyWord$Builder");
ObjectUtil TbKeyWordBuilderInc = new ObjectUtil(loader, packagz + ".TbKeyWord$Builder$Inc#INC");
TbKeyWordBuilder.invoke("update", 100l, TbKeyWordBuilderInc.getObject());
// 执行
// inc_f1 增加100
Object result = TbKeyWord.invoke("updateByExampleSelective", TbKeyWordBuilder.invoke("build"), TbKeyWordExample.getObject());
Assert.assertEquals(result, 1);
// 验证更新
ResultSet rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb_key_word where id = 1");
rs.first();
Assert.assertEquals(rs.getLong("update"), 101);
}
});
}
}
@@ -89,6 +89,91 @@ public class ModelBuilderPluginTest {
ObjectUtil tbKeys = new ObjectUtil(tbKeysBuilder.invoke("build"));
Assert.assertEquals(tbKeys.invoke("getKey1"), 50l);
Assert.assertEquals(tbKeys.invoke("getField1"), "ts2");
// 4. key and blobs
ObjectUtil TbKeysBlobsKeyBuilder = new ObjectUtil(loader, packagz + ".TbKeysBlobsKey$Builder");
TbKeysBlobsKeyBuilder.invoke("key1", 60l);
ObjectUtil TbKeysBlobsKey = new ObjectUtil(TbKeysBlobsKeyBuilder.invoke("build"));
Assert.assertEquals(TbKeysBlobsKey.invoke("getKey1"), 60l);
ObjectUtil TbKeysBlobsWithBLOBsBuilder = new ObjectUtil(loader, packagz + ".TbKeysBlobsWithBLOBs$Builder");
TbKeysBlobsWithBLOBsBuilder.invoke("key1", 90l);
TbKeysBlobsWithBLOBsBuilder.invoke("incF2", 70l);
TbKeysBlobsWithBLOBsBuilder.invoke("field2", "ts3");
ObjectUtil TbKeysBlobsWithBLOBs = new ObjectUtil(TbKeysBlobsWithBLOBsBuilder.invoke("build"));
Assert.assertEquals(TbKeysBlobsWithBLOBs.invoke("getKey1"), 90l);
Assert.assertEquals(TbKeysBlobsWithBLOBs.invoke("getIncF2"), 70l);
Assert.assertEquals(TbKeysBlobsWithBLOBs.invoke("getField2"), "ts3");
}
});
}
/**
* 测试静态builder方法
*/
@Test
public void testBuilderMethod() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ModelBuilderPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 普通model
ObjectUtil Tb = new ObjectUtil(loader, packagz + ".Tb");
ObjectUtil tbBuilder = new ObjectUtil(Tb.invoke("builder"));
tbBuilder.invoke("field1", "ts1");
tbBuilder.invoke("incF1", 100l);
ObjectUtil tb = new ObjectUtil(tbBuilder.invoke("build"));
Assert.assertEquals(tb.invoke("getField1"), "ts1");
Assert.assertEquals(tb.invoke("getIncF1"), 100l);
// 2. withBlobs
ObjectUtil TbBlobs = new ObjectUtil(loader, packagz + ".TbBlobs");
ObjectUtil tbBlobsBuilder = new ObjectUtil(TbBlobs.invoke("builder"));
tbBlobsBuilder.invoke("field1", "ts1");
ObjectUtil tbBlobs = new ObjectUtil(tbBlobsBuilder.invoke("build"));
Assert.assertEquals(tbBlobs.invoke("getField1"), "ts1");
ObjectUtil TbBlobsWithBLOBs= new ObjectUtil(loader, packagz + ".TbBlobsWithBLOBs");
ObjectUtil tbBlobsWithBLOBsBuilder = new ObjectUtil(TbBlobsWithBLOBs.invoke("builder"));
tbBlobsWithBLOBsBuilder.invoke("field1", "ts1");
tbBlobsWithBLOBsBuilder.invoke("field2", "ts2");
ObjectUtil tbBlobsWithBLOBs = new ObjectUtil(tbBlobsWithBLOBsBuilder.invoke("build"));
Assert.assertEquals(tbBlobsWithBLOBs.invoke("getField1"), "ts1");
Assert.assertEquals(tbBlobsWithBLOBs.invoke("getField2"), "ts2");
// 3. key
ObjectUtil TbKeysKey = new ObjectUtil(loader, packagz + ".TbKeysKey");
ObjectUtil tbKeysKeyBuilder = new ObjectUtil(TbKeysKey.invoke("builder"));
tbKeysKeyBuilder.invoke("key1", 60l);
ObjectUtil tbKeysKey = new ObjectUtil(tbKeysKeyBuilder.invoke("build"));
Assert.assertEquals(tbKeysKey.invoke("getKey1"), 60l);
ObjectUtil TbKeys = new ObjectUtil(loader, packagz + ".TbKeys");
ObjectUtil tbKeysBuilder = new ObjectUtil(TbKeys.invoke("builder"));
tbKeysBuilder.invoke("key1", 50l);
tbKeysBuilder.invoke("field1", "ts2");
ObjectUtil tbKeys = new ObjectUtil(tbKeysBuilder.invoke("build"));
Assert.assertEquals(tbKeys.invoke("getKey1"), 50l);
Assert.assertEquals(tbKeys.invoke("getField1"), "ts2");
// 4. key and blobs
ObjectUtil TbKeysBlobsKey = new ObjectUtil(loader, packagz + ".TbKeysBlobsKey");
ObjectUtil TbKeysBlobsKeyBuilder = new ObjectUtil(TbKeysBlobsKey.invoke("builder"));
TbKeysBlobsKeyBuilder.invoke("key1", 60l);
ObjectUtil tbKeysBlobsKey = new ObjectUtil(TbKeysBlobsKeyBuilder.invoke("build"));
Assert.assertEquals(tbKeysBlobsKey.invoke("getKey1"), 60l);
ObjectUtil TbKeysBlobsWithBLOBs = new ObjectUtil(loader, packagz + ".TbKeysBlobsWithBLOBs");
ObjectUtil TbKeysBlobsWithBLOBsBuilder = new ObjectUtil(TbKeysBlobsWithBLOBs.invoke("builder"));
TbKeysBlobsWithBLOBsBuilder.invoke("key1", 90l);
TbKeysBlobsWithBLOBsBuilder.invoke("incF2", 70l);
TbKeysBlobsWithBLOBsBuilder.invoke("field2", "ts3");
TbKeysBlobsWithBLOBs = new ObjectUtil(TbKeysBlobsWithBLOBsBuilder.invoke("build"));
Assert.assertEquals(TbKeysBlobsWithBLOBs.invoke("getKey1"), 90l);
Assert.assertEquals(TbKeysBlobsWithBLOBs.invoke("getIncF2"), 70l);
Assert.assertEquals(TbKeysBlobsWithBLOBs.invoke("getField2"), "ts3");
}
});
}
@@ -101,3 +101,20 @@ CREATE TABLE `tb_single_blob` (
INSERT INTO `tb_single_blob` VALUES ('1', 'fd1', '0', '1', '2', '3');
INSERT INTO `tb_single_blob` VALUES ('2', null, null, '3', '2', '1');
INSERT INTO `tb_single_blob` VALUES ('3', null, null, '1', '1', '1');
-- ----------------------------
-- Table structure for tb_key_word
-- ----------------------------
DROP TABLE IF EXISTS `tb_key_word`;
CREATE TABLE `tb_key_word` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field2` int(11) DEFAULT NULL,
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`update` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_key_word
-- ----------------------------
INSERT INTO `tb_key_word` VALUES ('1', '0', '0', '1');
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.IncrementsPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin" />
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb_key_word">
<property name="incrementsColumns" value="update"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
@@ -70,3 +70,22 @@ CREATE TABLE `tb_keys` (
-- Records of tb_keys
-- ----------------------------
-- ----------------------------
-- Table structure for tb_keys_blobs
-- ----------------------------
DROP TABLE IF EXISTS `tb_keys_blobs`;
CREATE TABLE `tb_keys_blobs` (
`key1` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`key2` varchar(255) NOT NULL,
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` longtext COMMENT '注释2',
`field3` longtext,
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
-- ----------------------------
@@ -49,5 +49,6 @@
<table tableName="tb_blobs">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys_blobs"/>
</context>
</generatorConfiguration>