From 79b36e8a7f1455f96448a9c4af0e3659abbda685 Mon Sep 17 00:00:00 2001 From: hewei Date: Wed, 21 Jun 2017 18:40:26 +0800 Subject: [PATCH] =?UTF-8?q?upsert=E5=92=8C=E5=A2=9E=E9=87=8F=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E6=95=B4=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../generator/plugins/IncrementsPlugin.java | 96 ++-------- .../generator/plugins/ModelBuilderPlugin.java | 139 +++++++------- .../plugins/SelectiveEnhancedPlugin.java | 1 + .../generator/plugins/UpsertPlugin.java | 88 +++++++-- .../plugins/utils/IncrementsPluginTools.java | 171 ++++++++++++++++++ .../utils/XmlElementGeneratorTools.java | 32 ++-- 6 files changed, 336 insertions(+), 191 deletions(-) create mode 100644 src/main/java/com/itfsw/mybatis/generator/plugins/utils/IncrementsPluginTools.java diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/IncrementsPlugin.java b/src/main/java/com/itfsw/mybatis/generator/plugins/IncrementsPlugin.java index 4a39740..8c2a4f9 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/IncrementsPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/IncrementsPlugin.java @@ -17,17 +17,15 @@ 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 org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.dom.java.TopLevelClass; -import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.Element; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; -import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities; -import org.mybatis.generator.internal.util.StringUtility; import java.util.ArrayList; import java.util.List; @@ -42,7 +40,7 @@ import java.util.List; */ public class IncrementsPlugin extends BasePlugin { public static final String PRE_INCREMENTS_COLUMNS = "incrementsColumns"; // incrementsColumns property - private List columns; // 需要进行自增的字段 + private IncrementsPluginTools incTools; // 增量插件工具 /** * 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html @@ -67,22 +65,7 @@ public class IncrementsPlugin extends BasePlugin { */ @Override public void initialized(IntrospectedTable introspectedTable) { - this.columns = new ArrayList<>(); - // 获取表配置信息 - String incrementsColumns = introspectedTable.getTableConfigurationProperty(IncrementsPlugin.PRE_INCREMENTS_COLUMNS); - if (StringUtility.stringHasValue(incrementsColumns)) { - // 切分 - String[] incrementsColumnsStrs = incrementsColumns.split(","); - List columns = introspectedTable.getAllColumns(); - for (String incrementsColumnsStr : incrementsColumnsStrs) { - IntrospectedColumn column = introspectedTable.getColumn(incrementsColumnsStr); - if (column == null) { - logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件没有找到column为" + incrementsColumnsStr + "的字段!"); - } else if (columns.indexOf(column) != -1) { - this.columns.add(column); - } - } - } + this.incTools = IncrementsPluginTools.getTools(context, introspectedTable); } /** @@ -181,26 +164,13 @@ public class IncrementsPlugin extends BasePlugin { return true; } - /** - * 是否需要替换 - * @param columnName - * @return - */ - private boolean needReplace(String columnName) { - for (IntrospectedColumn introspectedColumn : this.columns) { - if (introspectedColumn.getActualColumnName().equals(columnName)) { - return true; - } - } - return false; - } /** * 有Selective代码生成 * @param element */ private void generatedWithSelective(XmlElement element, IntrospectedTable introspectedTable, boolean hasPrefix) { - if (columns.size() > 0) { + if (incTools.support()) { // 查找 set->if->text List sets = XmlElementGeneratorTools.findXmlElements(element, "set"); if (sets.size() > 0) { @@ -212,11 +182,11 @@ 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); // 查找是否需要进行增量操作 - if (needReplace(columnName)) { - IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName); + if (incTools.supportColumn(introspectedColumn)) { xmlElement.getElements().clear(); - xmlElement.getElements().addAll(generatedIncrementsElement(xmlElement, introspectedColumn, hasPrefix, true)); + xmlElement.getElements().addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, true)); } } } @@ -231,7 +201,7 @@ public class IncrementsPlugin extends BasePlugin { * @param hasPrefix */ private void generatedWithoutSelective(XmlElement xmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) { - if (columns.size() > 0) { + if (incTools.support()) { List newEles = new ArrayList<>(); for (Element ele : xmlElement.getElements()) { // 找到text节点且格式为 set xx = xx 或者 xx = xx @@ -241,11 +211,10 @@ public class IncrementsPlugin extends BasePlugin { // 清理 set 操作 text = text.replaceFirst("set\\s", "").trim(); String columnName = text.split("=")[0].trim(); - + IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName); // 查找判断是否需要进行节点替换 - if (needReplace(columnName)) { - IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName); - newEles.addAll(generatedIncrementsElement(xmlElement, introspectedColumn, hasPrefix, text.endsWith(","))); + if (incTools.supportColumn(introspectedColumn)) { + newEles.addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, text.endsWith(","))); continue; } @@ -259,47 +228,4 @@ public class IncrementsPlugin extends BasePlugin { xmlElement.getElements().addAll(newEles); } } - - /** - * 生成增量操作节点 - * @param element - * @param introspectedColumn - * @param hasPrefix - * @param hasComma - */ - private List generatedIncrementsElement(XmlElement element, IntrospectedColumn introspectedColumn, boolean hasPrefix, boolean hasComma) { - List list = new ArrayList<>(); - - // 1. column = 节点 - list.add(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = ")); - - // 2. 选择节点 - // 条件 - XmlElement choose = new XmlElement("choose"); - - // 没有启用增量操作 - XmlElement when = new XmlElement("when"); - when.addAttribute(new Attribute("test", (hasPrefix ? "record" : "_parameter") + ".incs.isEmpty()")); - TextElement normal = new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null)); - when.addElement(normal); - choose.addElement(when); - - // 启用了增量操作 - XmlElement otherwise = new XmlElement("otherwise"); - TextElement spec = new TextElement( - MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) - + " ${" + (hasPrefix ? "record" : "_parameter") + ".incs." + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ".value} " - + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null)); - otherwise.addElement(spec); - choose.addElement(otherwise); - - list.add(choose); - - // 3. 结尾逗号 - if (hasComma) { - list.add(new TextElement(",")); - } - - return list; - } } diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/ModelBuilderPlugin.java b/src/main/java/com/itfsw/mybatis/generator/plugins/ModelBuilderPlugin.java index a15ae22..e0ba203 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/ModelBuilderPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/ModelBuilderPlugin.java @@ -17,14 +17,13 @@ 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.PluginTools; import com.itfsw.mybatis.generator.plugins.utils.enhanced.JavaElementEnhanced; 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 org.mybatis.generator.internal.util.StringUtility; import java.util.List; @@ -38,7 +37,6 @@ import java.util.List; */ public class ModelBuilderPlugin extends BasePlugin { public static final String BUILDER_CLASS_NAME = "Builder"; // Builder 类名 - private FullyQualifiedJavaType inc; // 是否支持Increments /** * Model Methods 生成 @@ -133,83 +131,76 @@ public class ModelBuilderPlugin extends BasePlugin { // ========================================== IncrementsPlugin ======================================= - if (PluginTools.getPluginConfiguration(context, IncrementsPlugin.class) != null) { - String incrementsColumns = introspectedTable.getTableConfigurationProperty(IncrementsPlugin.PRE_INCREMENTS_COLUMNS); - if (StringUtility.stringHasValue(incrementsColumns)) { - if (modelBaseRecord) { - this.inc = new FullyQualifiedJavaType(topLevelClass.getType().getShortName() + "." + BUILDER_CLASS_NAME + ".Inc"); - // 增加枚举 - 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); + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable); + 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); - 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); - logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。"); + 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); + logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。"); - 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( - "incs", - JavaVisibility.PROTECTED, - new FullyQualifiedJavaType("Map"), - "new HashMap()" + innerClass.addInnerEnum(eIncrements); + // 增加field + Field fIncrements = JavaElementGeneratorTools.generateField( + "incs", + JavaVisibility.PROTECTED, + new FullyQualifiedJavaType("Map"), + "new HashMap()" + ); + 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); + } + + // Builder 中 添加字段支持 + for (IntrospectedColumn column : columns) { + if (incTools.supportColumn(column)) { + Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable); + // 增加方法 + Method mIncrements = JavaElementGeneratorTools.generateMethod( + field.getName(), + JavaVisibility.PUBLIC, + innerClass.getType(), + new Parameter(field.getType(), field.getName()), + new Parameter(incTools.getIncEnum(), "inc") ); - 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); - } + commentGenerator.addSetterComment(mIncrements, introspectedTable, column); - // 切分 - String[] incrementsColumnsStrs = incrementsColumns.split(","); - for (String incrementsColumnsStr : incrementsColumnsStrs) { - IntrospectedColumn column = introspectedTable.getColumn(incrementsColumnsStr); - if (column == null) { - logger.warn("itfsw:插件" + IncrementsPlugin.class.getTypeName() + "插件没有找到column为" + incrementsColumnsStr + "的字段!"); - } else if (columns.indexOf(column) != -1) { - Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable); - // 增加方法 - Method mIncrements = JavaElementGeneratorTools.generateMethod( - field.getName(), - JavaVisibility.PUBLIC, - innerClass.getType(), - new Parameter(field.getType(), field.getName()), - new Parameter(this.inc, "inc") - ); - commentGenerator.addSetterComment(mIncrements, introspectedTable, column); + Method setterMethod = JavaBeansUtil.getJavaBeansSetter(column, context, introspectedTable); + mIncrements.addBodyLine("obj.incs.put(\"" + column.getActualColumnName() + "\", inc);"); + mIncrements.addBodyLine("obj." + setterMethod.getName() + "(" + field.getName() + ");"); + mIncrements.addBodyLine("return this;"); - Method setterMethod = JavaBeansUtil.getJavaBeansSetter(column, context, introspectedTable); - mIncrements.addBodyLine("obj.incs.put(\"" + column.getActualColumnName() + "\", inc);"); - mIncrements.addBodyLine("obj." + setterMethod.getName() + "(" + field.getName() + ");"); - mIncrements.addBodyLine("return this;"); - - JavaElementEnhanced.addMethodWithBestPosition(innerClass, mIncrements); - } + JavaElementEnhanced.addMethodWithBestPosition(innerClass, mIncrements); } } } diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/SelectiveEnhancedPlugin.java b/src/main/java/com/itfsw/mybatis/generator/plugins/SelectiveEnhancedPlugin.java index 66f3f68..ad6e31a 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/SelectiveEnhancedPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/SelectiveEnhancedPlugin.java @@ -211,6 +211,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin { XmlElement whenEle = new XmlElement("when"); whenEle.addAttribute(new Attribute("test", prefix + "isSelective()")); for (Element ele : element.getElements()) { + logger.warn(ele.getFormattedContent(0)); // 对于字符串主键,是没有if判断节点的 if (ele instanceof XmlElement){ // if的text节点 diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/UpsertPlugin.java b/src/main/java/com/itfsw/mybatis/generator/plugins/UpsertPlugin.java index ef496f0..c8462ca 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/UpsertPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/UpsertPlugin.java @@ -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.IncrementsPluginTools; import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools; import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools; import org.mybatis.generator.api.IntrospectedColumn; @@ -26,6 +27,7 @@ import org.mybatis.generator.api.dom.xml.*; import org.mybatis.generator.codegen.mybatis3.ListUtilities; import org.mybatis.generator.internal.util.StringUtility; +import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -243,9 +245,8 @@ public class UpsertPlugin extends BasePlugin { eleUpsertWithBLOBs.addElement(element); } eleUpsertWithBLOBs.addElement(new TextElement("on duplicate key update ")); - for (Element element : XmlElementGeneratorTools.generateSets(introspectedTable.getAllColumns())) { - eleUpsertWithBLOBs.addElement(element); - } + // set 操作增加增量插件支持 + this.incrementsSupport(eleUpsertWithBLOBs, XmlElementGeneratorTools.generateSets(introspectedTable.getAllColumns()), introspectedTable, false); document.getRootElement().addElement(eleUpsertWithBLOBs); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。"); @@ -268,7 +269,8 @@ public class UpsertPlugin extends BasePlugin { 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)); + // set 操作增加增量插件支持 + this.incrementsSelectiveSupport(eleUpsertSelectiveWithBLOBs, XmlElementGeneratorTools.generateSetsSelective(introspectedTable.getAllColumns(), null, false), introspectedTable, false); document.getRootElement().addElement(eleUpsertSelectiveWithBLOBs); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。"); @@ -298,9 +300,8 @@ public class UpsertPlugin extends BasePlugin { // update eleUpsertByExampleWithBLOBs.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExampleWithBLOBs.addElement(new TextElement("set")); - for (Element element : XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record.")) { - eleUpsertByExampleWithBLOBs.addElement(element); - } + // set 操作增加增量插件支持 + this.incrementsSupport(eleUpsertByExampleWithBLOBs, XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record."), introspectedTable, true); // update where eleUpsertByExampleWithBLOBs.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -330,7 +331,9 @@ public class UpsertPlugin extends BasePlugin { // update eleUpsertByExampleSelectiveWithBLOBs.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExampleSelectiveWithBLOBs.addElement(new TextElement("set")); - eleUpsertByExampleSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record.")); + // set 操作增加增量插件支持 + this.incrementsSelectiveSupport(eleUpsertByExampleSelectiveWithBLOBs, XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "record."), introspectedTable, true); + // update where eleUpsertByExampleSelectiveWithBLOBs.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -372,9 +375,9 @@ public class UpsertPlugin extends BasePlugin { eleUpsert.addElement(element); } eleUpsert.addElement(new TextElement("on duplicate key update ")); - for (Element element : XmlElementGeneratorTools.generateSets(columns)) { - eleUpsert.addElement(element); - } + // set 操作增加增量插件支持 + this.incrementsSupport(eleUpsert, XmlElementGeneratorTools.generateSets(columns), introspectedTable, false); + document.getRootElement().addElement(eleUpsert); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。"); @@ -397,7 +400,8 @@ public class UpsertPlugin extends BasePlugin { eleUpsertSelective.addElement(new TextElement("values")); eleUpsertSelective.addElement(XmlElementGeneratorTools.generateValuesSelective(columns)); eleUpsertSelective.addElement(new TextElement("on duplicate key update ")); - eleUpsertSelective.addElement(XmlElementGeneratorTools.generateSetsSelective(columns, null, false)); + // set 操作增加增量插件支持 + this.incrementsSelectiveSupport(eleUpsertSelective, XmlElementGeneratorTools.generateSetsSelective(columns, null, false), introspectedTable, false); document.getRootElement().addElement(eleUpsertSelective); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。"); @@ -427,9 +431,9 @@ public class UpsertPlugin extends BasePlugin { // update eleUpsertByExample.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExample.addElement(new TextElement("set")); - for (Element element : XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record.")) { - eleUpsertByExample.addElement(element); - } + // set 操作增加增量插件支持 + this.incrementsSupport(eleUpsertByExample, XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record."), introspectedTable, true); + // update where eleUpsertByExample.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -458,7 +462,8 @@ public class UpsertPlugin extends BasePlugin { // update eleUpsertByExampleSelective.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExampleSelective.addElement(new TextElement("set")); - eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record.")); + // set 操作增加增量插件支持 + this.incrementsSelectiveSupport(eleUpsertByExampleSelective, XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record."), introspectedTable, true); // update where eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -496,4 +501,55 @@ public class UpsertPlugin extends BasePlugin { element.addElement(new TextElement(")")); } + /** + * 增量操作支持 + * @param xmlElement + * @param trimXmlElement + * @param introspectedTable + * @param hasPrefix + */ + private void incrementsSelectiveSupport(XmlElement xmlElement, XmlElement trimXmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) { + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable); + if (incTools.support()) { + List ifs = new ArrayList<>(); + // 获取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); + if (incTools.supportColumn(introspectedColumn)) { + // if 节点数据替换 + ((XmlElement) element).getElements().clear(); + ((XmlElement) element).getElements().addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, true)); + continue; + } + ifs.add(element); + } + } + xmlElement.addElement(trimXmlElement); + } + + /** + * 增量操作支持 + * @param xmlElement + * @param elements + * @param introspectedTable + * @param hasPrefix + */ + private void incrementsSupport(XmlElement xmlElement, List elements, IntrospectedTable introspectedTable, boolean hasPrefix) { + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable); + for (TextElement element : elements) { + if (incTools.support()) { + // 获取column + String text = element.getContent().trim(); + String columnName = text.split("=")[0].trim().replaceAll("`", "").replaceAll("\"", "").replaceAll("'", ""); + IntrospectedColumn introspectedColumn = introspectedTable.getColumn(columnName); + if (incTools.supportColumn(introspectedColumn)) { + xmlElement.getElements().addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, text.endsWith(","))); + continue; + } + } + xmlElement.addElement(element); + } + } } \ No newline at end of file diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/utils/IncrementsPluginTools.java b/src/main/java/com/itfsw/mybatis/generator/plugins/utils/IncrementsPluginTools.java new file mode 100644 index 0000000..e62c598 --- /dev/null +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/utils/IncrementsPluginTools.java @@ -0,0 +1,171 @@ +/* + * 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; + +import com.itfsw.mybatis.generator.plugins.IncrementsPlugin; +import com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin; +import org.mybatis.generator.api.IntrospectedColumn; +import org.mybatis.generator.api.IntrospectedTable; +import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; +import org.mybatis.generator.api.dom.xml.Attribute; +import org.mybatis.generator.api.dom.xml.Element; +import org.mybatis.generator.api.dom.xml.TextElement; +import org.mybatis.generator.api.dom.xml.XmlElement; +import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities; +import org.mybatis.generator.config.Context; +import org.mybatis.generator.internal.util.StringUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * --------------------------------------------------------------------------- + * 增量插件工具 + * --------------------------------------------------------------------------- + * @author: hewei + * @time:2017/6/21 16:12 + * --------------------------------------------------------------------------- + */ +public class IncrementsPluginTools { + private final static Logger logger = LoggerFactory.getLogger(IncrementsPluginTools.class); + private Context context; // 上下文 + private IntrospectedTable introspectedTable; // 表 + private List columns = new ArrayList<>(); // 表启用增量操作的字段 + + /** + * 构造函数 + * @param context + * @param introspectedTable + */ + private IncrementsPluginTools(Context context, IntrospectedTable introspectedTable) { + this.context = context; + this.introspectedTable = introspectedTable; + } + + /** + * 获取工具 + * @param context + * @param introspectedTable + * @return + */ + public static IncrementsPluginTools getTools(Context context, IntrospectedTable introspectedTable) { + IncrementsPluginTools tools = new IncrementsPluginTools(context, introspectedTable); + // 判断是否启用了插件 + if (PluginTools.getPluginConfiguration(context, IncrementsPlugin.class) != null) { + String incrementsColumns = introspectedTable.getTableConfigurationProperty(IncrementsPlugin.PRE_INCREMENTS_COLUMNS); + if (StringUtility.stringHasValue(incrementsColumns)) { + // 切分 + String[] incrementsColumnsStrs = incrementsColumns.split(","); + for (String incrementsColumnsStr : incrementsColumnsStrs) { + IntrospectedColumn column = introspectedTable.getColumn(incrementsColumnsStr.trim()); + if (column == null) { + logger.warn("itfsw:插件" + IncrementsPlugin.class.getTypeName() + "插件没有找到column为" + incrementsColumnsStr.trim() + "的字段!"); + } else { + tools.columns.add(column); + } + } + } + } + return tools; + } + + /** + * 获取INC Enum + * @return + */ + public FullyQualifiedJavaType getIncEnum() { + return new FullyQualifiedJavaType(this.introspectedTable.getFullyQualifiedTable().getDomainObjectName() + "." + ModelBuilderPlugin.BUILDER_CLASS_NAME + ".Inc"); + } + + /** + * 是否启用了 + * + * @return + */ + public boolean support(){ + return this.columns.size() > 0; + } + + /** + * Getter method for property columns. + * @return property value of columns + * @author hewei + */ + public List getColumns() { + return columns; + } + + /** + * 判断是否为需要进行增量操作的column + * + * @param searchColumn + * @return + */ + public boolean supportColumn(IntrospectedColumn searchColumn){ + for (IntrospectedColumn column: this.columns){ + if (column.getActualColumnName().equals(searchColumn.getActualColumnName())){ + return true; + } + } + return false; + } + + /** + * 生成增量操作节点 + * + * @param introspectedColumn + * @param hasPrefix + * @param hasComma + */ + public List generatedIncrementsElement(IntrospectedColumn introspectedColumn, boolean hasPrefix, boolean hasComma) { + List list = new ArrayList<>(); + + // 1. column = 节点 + list.add(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = ")); + + // 2. 选择节点 + // 条件 + XmlElement choose = new XmlElement("choose"); + + // 没有启用增量操作 + XmlElement when = new XmlElement("when"); + when.addAttribute(new Attribute("test", (hasPrefix ? "record" : "_parameter") + ".incs.isEmpty()")); + TextElement normal = new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null)); + when.addElement(normal); + choose.addElement(when); + + // 启用了增量操作 + XmlElement otherwise = new XmlElement("otherwise"); + TextElement spec = new TextElement( + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + + " ${" + (hasPrefix ? "record" : "_parameter") + ".incs." + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ".value} " + + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null)); + otherwise.addElement(spec); + choose.addElement(otherwise); + + list.add(choose); + + // 3. 结尾逗号 + if (hasComma) { + list.add(new TextElement(",")); + } + + return list; + } +} diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/utils/XmlElementGeneratorTools.java b/src/main/java/com/itfsw/mybatis/generator/plugins/utils/XmlElementGeneratorTools.java index b7d2107..e16b764 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/utils/XmlElementGeneratorTools.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/utils/XmlElementGeneratorTools.java @@ -137,7 +137,7 @@ public class XmlElementGeneratorTools { * @param columns * @return */ - public static List generateKeys(List columns) { + public static List generateKeys(List columns) { return generateKeys(columns, true); } @@ -147,7 +147,7 @@ public class XmlElementGeneratorTools { * @param bracket * @return */ - public static List generateKeys(List columns, boolean bracket) { + public static List generateKeys(List columns, boolean bracket) { return generateCommColumns(columns, null, bracket, 1); } @@ -177,7 +177,7 @@ public class XmlElementGeneratorTools { * @param bracket * @return */ - public static Element generateKeysSelective(List columns, String prefix, boolean bracket) { + public static XmlElement generateKeysSelective(List columns, String prefix, boolean bracket) { return generateCommColumnsSelective(columns, prefix, bracket, 1); } @@ -186,7 +186,7 @@ public class XmlElementGeneratorTools { * @param columns * @return */ - public static List generateValues(List columns) { + public static List generateValues(List columns) { return generateValues(columns, null); } @@ -196,7 +196,7 @@ public class XmlElementGeneratorTools { * @param prefix * @return */ - public static List generateValues(List columns, String prefix) { + public static List generateValues(List columns, String prefix) { return generateValues(columns, prefix, true); } @@ -207,7 +207,7 @@ public class XmlElementGeneratorTools { * @param bracket * @return */ - public static List generateValues(List columns, String prefix, boolean bracket) { + public static List generateValues(List columns, String prefix, boolean bracket) { return generateCommColumns(columns, prefix, bracket, 2); } @@ -237,7 +237,7 @@ public class XmlElementGeneratorTools { * @param bracket * @return */ - public static Element generateValuesSelective(List columns, String prefix, boolean bracket) { + public static XmlElement generateValuesSelective(List columns, String prefix, boolean bracket) { return generateCommColumnsSelective(columns, prefix, bracket, 2); } @@ -246,7 +246,7 @@ public class XmlElementGeneratorTools { * @param columns * @return */ - public static List generateSets(List columns) { + public static List generateSets(List columns) { return generateSets(columns, null, false); } @@ -256,7 +256,7 @@ public class XmlElementGeneratorTools { * @param prefix * @return */ - public static List generateSets(List columns, String prefix) { + public static List generateSets(List columns, String prefix) { return generateSets(columns, prefix, false); } @@ -267,7 +267,7 @@ public class XmlElementGeneratorTools { * @param bracket * @return */ - public static List generateSets(List columns, String prefix, boolean bracket) { + public static List generateSets(List columns, String prefix, boolean bracket) { return generateCommColumns(columns, prefix, bracket, 3); } @@ -276,7 +276,7 @@ public class XmlElementGeneratorTools { * @param columns * @return */ - public static Element generateSetsSelective(List columns) { + public static XmlElement generateSetsSelective(List columns) { return generateSetsSelective(columns, null, false); } @@ -286,7 +286,7 @@ public class XmlElementGeneratorTools { * @param prefix * @return */ - public static Element generateSetsSelective(List columns, String prefix) { + public static XmlElement generateSetsSelective(List columns, String prefix) { return generateSetsSelective(columns, prefix, false); } @@ -297,7 +297,7 @@ public class XmlElementGeneratorTools { * @param bracket * @return */ - public static Element generateSetsSelective(List columns, String prefix, boolean bracket) { + public static XmlElement generateSetsSelective(List columns, String prefix, boolean bracket) { return generateCommColumnsSelective(columns, prefix, bracket, 3); } @@ -309,8 +309,8 @@ public class XmlElementGeneratorTools { * @param type 1:key,2:value,3:set * @return */ - private static List generateCommColumns(List columns, String prefix, boolean bracket, int type) { - List list = new ArrayList<>(); + private static List generateCommColumns(List columns, String prefix, boolean bracket, int type) { + List list = new ArrayList<>(); StringBuilder sb = new StringBuilder(bracket ? "(" : ""); Iterator columnIterator = columns.iterator(); while (columnIterator.hasNext()) { @@ -361,7 +361,7 @@ public class XmlElementGeneratorTools { * @param type 1:key,2:value,3:set * @return */ - private static Element generateCommColumnsSelective(List columns, String prefix, boolean bracket, int type) { + private static XmlElement generateCommColumnsSelective(List columns, String prefix, boolean bracket, int type) { XmlElement eleTrim = new XmlElement("trim"); if (bracket) { eleTrim.addAttribute(new Attribute("prefix", "("));