From a8a788f195f4bd33aa1013b80e6a2a454369eb8b Mon Sep 17 00:00:00 2001 From: hewei Date: Tue, 24 Apr 2018 13:35:16 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=96=B0=E6=95=B4=E5=90=88=20Incremen?= =?UTF-8?q?tsPlugin=20=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../generator/plugins/IncrementsPlugin.java | 4 +- .../plugins/SelectiveEnhancedPlugin.java | 67 +++++-- .../generator/plugins/UpsertPlugin.java | 175 ++++++++++-------- .../plugins/utils/IncrementsPluginTools.java | 117 +++++++++++- .../plugins/IncrementsPluginTest.java | 100 +++++++++- .../OldSelectiveEnhancedPluginTest.java | 2 +- .../generator/plugins/UpsertPluginTest.java | 4 +- ...nerator-with-selective-enhanced-plugin.xml | 64 +++++++ 8 files changed, 430 insertions(+), 103 deletions(-) create mode 100644 src/test/resources/scripts/IncrementsPlugin/mybatis-generator-with-selective-enhanced-plugin.xml 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 5b4e05b..acade52 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/IncrementsPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/IncrementsPlugin.java @@ -195,7 +195,7 @@ public class IncrementsPlugin extends BasePlugin { // 查找是否需要进行增量操作 if (incTools.supportColumn(introspectedColumn)) { xmlElement.getElements().clear(); - xmlElement.getElements().addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, true)); + xmlElement.getElements().addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix ? "record." : null, true)); } } } @@ -223,7 +223,7 @@ public class IncrementsPlugin extends BasePlugin { IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName); // 查找判断是否需要进行节点替换 if (incTools.supportColumn(introspectedColumn)) { - newEles.addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix, text.endsWith(","))); + newEles.addAll(incTools.generatedIncrementsElement(introspectedColumn, hasPrefix ? "record." : null, text.endsWith(","))); continue; } 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 259d590..1c51d2b 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/SelectiveEnhancedPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/SelectiveEnhancedPlugin.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.PluginTools; import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools; import org.mybatis.generator.api.IntrospectedColumn; @@ -200,7 +201,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin { answer.addElement(insertChooseEle); XmlElement insertWhenEle = new XmlElement("when"); - insertWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); insertChooseEle.addElement(insertWhenEle); XmlElement insertForeachEle = new XmlElement("foreach"); @@ -230,7 +231,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin { answer.addElement(valuesChooseEle); XmlElement valuesWhenEle = new XmlElement("when"); - valuesWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + valuesWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); valuesChooseEle.addElement(valuesWhenEle); XmlElement valuesForeachEle = new XmlElement("foreach"); @@ -267,6 +268,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin { */ @Override public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings); // 清空 XmlElement answer = element; answer.getElements().clear(); @@ -283,26 +285,43 @@ public class SelectiveEnhancedPlugin extends BasePlugin { answer.addElement(new TextElement(sb.toString())); // selective + answer.addElement(new TextElement("SET")); XmlElement setChooseEle = new XmlElement("choose"); answer.addElement(setChooseEle); XmlElement setWhenEle = new XmlElement("when"); - setWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); setChooseEle.addElement(setWhenEle); XmlElement setForeachEle = new XmlElement("foreach"); setForeachEle.addAttribute(new Attribute("collection", "selective")); setForeachEle.addAttribute(new Attribute("item", "column")); - setForeachEle.addAttribute(new Attribute("open", "SET")); setForeachEle.addAttribute(new Attribute("separator", ",")); - setForeachEle.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}")); + // 自增插件支持 + if (incTools.support()) { + incTools.generateSetsSelectiveWithSelectiveEnhancedPlugin(setForeachEle); + } else { + setForeachEle.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}")); + } setWhenEle.addElement(setForeachEle); XmlElement setOtherwiseEle = new XmlElement("otherwise"); - setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( - ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns()), - "record." - )); + + // 自增插件支持 + if (incTools.support()) { + setOtherwiseEle.addElement(incTools.generateSetsSelective( + ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + + )); + } else { + setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( + ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record." + )); + } + setChooseEle.addElement(setOtherwiseEle); answer.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -319,6 +338,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin { */ @Override public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings); // 清空 XmlElement answer = element; answer.getElements().clear(); @@ -336,27 +356,42 @@ public class SelectiveEnhancedPlugin extends BasePlugin { answer.addElement(new TextElement(sb.toString())); // selective + answer.addElement(new TextElement("SET")); XmlElement setChooseEle = new XmlElement("choose"); answer.addElement(setChooseEle); XmlElement setWhenEle = new XmlElement("when"); - setWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); setChooseEle.addElement(setWhenEle); XmlElement setForeachEle = new XmlElement("foreach"); setForeachEle.addAttribute(new Attribute("collection", "selective")); setForeachEle.addAttribute(new Attribute("item", "column")); - setForeachEle.addAttribute(new Attribute("open", "SET")); setForeachEle.addAttribute(new Attribute("separator", ",")); - setForeachEle.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}")); + // 自增插件支持 + if (incTools.support()) { + incTools.generateSetsSelectiveWithSelectiveEnhancedPlugin(setForeachEle); + } else { + setForeachEle.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}")); + } setWhenEle.addElement(setForeachEle); XmlElement setOtherwiseEle = new XmlElement("otherwise"); - setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( - ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getNonPrimaryKeyColumns()), - "record." - )); setChooseEle.addElement(setOtherwiseEle); + // 自增插件支持 + if (incTools.support()) { + setOtherwiseEle.addElement(incTools.generateSetsSelective( + ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getNonPrimaryKeyColumns()), + "record.", + false + + )); + } else { + setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( + ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getNonPrimaryKeyColumns()), + "record." + )); + } XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(answer, introspectedTable.getPrimaryKeyColumns(), "record."); 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 1b0712d..c4076b6 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/UpsertPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/UpsertPlugin.java @@ -24,7 +24,6 @@ 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; @@ -173,7 +172,7 @@ public class UpsertPlugin extends BasePlugin { new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record", "@Param(\"record\")"), new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")") ); - if (withSelectiveEnhancedPlugin){ + if (withSelectiveEnhancedPlugin) { // column枚举 FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME); mUpsertByExampleSelective.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true)); @@ -209,6 +208,7 @@ public class UpsertPlugin extends BasePlugin { */ private void generateXmlElementWithSelective(Document document, IntrospectedTable introspectedTable) { List columns = ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns()); + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings); if (withSelectiveEnhancedPlugin) { // ====================================== upsertSelective ====================================== @@ -230,7 +230,7 @@ public class UpsertPlugin extends BasePlugin { eleUpsertSelective.addElement(insertChooseEle); XmlElement insertWhenEle = new XmlElement("when"); - insertWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); insertChooseEle.addElement(insertWhenEle); XmlElement insertForeachEle = new XmlElement("foreach"); @@ -260,7 +260,7 @@ public class UpsertPlugin extends BasePlugin { eleUpsertSelective.addElement(valuesChooseEle); XmlElement valuesWhenEle = new XmlElement("when"); - valuesWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + valuesWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); valuesChooseEle.addElement(valuesWhenEle); XmlElement valuesForeachEle = new XmlElement("foreach"); @@ -292,7 +292,7 @@ public class UpsertPlugin extends BasePlugin { eleUpsertSelective.addElement(setChooseEle); XmlElement setWhenEle = new XmlElement("when"); - setWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); setChooseEle.addElement(setWhenEle); XmlElement setForeachEle = new XmlElement("foreach"); @@ -304,7 +304,19 @@ public class UpsertPlugin extends BasePlugin { XmlElement setOtherwiseEle = new XmlElement("otherwise"); // set 操作增加增量插件支持 - this.incrementsSelectiveSupport(setOtherwiseEle, XmlElementGeneratorTools.generateSetsSelective(columns, "record.", false), introspectedTable, false); + if (incTools.support()) { + setOtherwiseEle.addElement(incTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + )); + } else { + setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + )); + } setChooseEle.addElement(setOtherwiseEle); @@ -330,7 +342,7 @@ public class UpsertPlugin extends BasePlugin { eleUpsertByExampleSelective.addElement(insertChooseEle); insertWhenEle = new XmlElement("when"); - insertWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); insertChooseEle.addElement(insertWhenEle); insertForeachEle = new XmlElement("foreach"); @@ -369,7 +381,7 @@ public class UpsertPlugin extends BasePlugin { eleUpsertByExampleSelective.addElement(setChooseEle); setWhenEle = new XmlElement("when"); - setWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); setChooseEle.addElement(setWhenEle); setForeachEle = new XmlElement("foreach"); @@ -380,10 +392,21 @@ public class UpsertPlugin extends BasePlugin { setWhenEle.addElement(setForeachEle); setOtherwiseEle = new XmlElement("otherwise"); - setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( - ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), - "record." - )); + + // set 操作增加增量插件支持 + if (incTools.support()) { + setOtherwiseEle.addElement(incTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + )); + } else { + setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + )); + } setChooseEle.addElement(setOtherwiseEle); // update where @@ -412,7 +435,19 @@ public class UpsertPlugin extends BasePlugin { eleUpsertSelective.addElement(XmlElementGeneratorTools.generateValuesSelective(columns)); eleUpsertSelective.addElement(new TextElement("on duplicate key update ")); // set 操作增加增量插件支持 - this.incrementsSelectiveSupport(eleUpsertSelective, XmlElementGeneratorTools.generateSetsSelective(columns, null, false), introspectedTable, false); + if (incTools.support()) { + eleUpsertSelective.addElement(incTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + null, + false + )); + } else { + eleUpsertSelective.addElement(XmlElementGeneratorTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + null, + false + )); + } document.getRootElement().addElement(eleUpsertSelective); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。"); @@ -440,7 +475,19 @@ public class UpsertPlugin extends BasePlugin { eleUpsertByExampleSelective.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExampleSelective.addElement(new TextElement("set")); // set 操作增加增量插件支持 - this.incrementsSelectiveSupport(eleUpsertByExampleSelective, XmlElementGeneratorTools.generateSetsSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record."), introspectedTable, true); + if (incTools.support()) { + eleUpsertByExampleSelective.addElement(incTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + )); + } else { + eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.generateSetsSelective( + ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), + "record.", + false + )); + } // update where eleUpsertByExampleSelective.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -457,6 +504,8 @@ public class UpsertPlugin extends BasePlugin { * @param introspectedTable */ private void generateXmlElementWithBLOBs(Document document, IntrospectedTable introspectedTable) { + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings); + if (introspectedTable.hasBLOBColumns()) { List columns = ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns()); // ====================================== upsertWithBLOBs ====================================== @@ -482,7 +531,15 @@ public class UpsertPlugin extends BasePlugin { } eleUpsertWithBLOBs.addElement(new TextElement("on duplicate key update ")); // set 操作增加增量插件支持 - this.incrementsSupport(eleUpsertWithBLOBs, XmlElementGeneratorTools.generateSets(columns), introspectedTable, false); + if (incTools.support()) { + for (Element ele : incTools.generateSets(columns, null, false)) { + eleUpsertWithBLOBs.addElement(ele); + } + } else { + for (Element ele : XmlElementGeneratorTools.generateSets(columns)) { + eleUpsertWithBLOBs.addElement(ele); + } + } document.getRootElement().addElement(eleUpsertWithBLOBs); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。"); @@ -513,7 +570,15 @@ public class UpsertPlugin extends BasePlugin { eleUpsertByExampleWithBLOBs.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExampleWithBLOBs.addElement(new TextElement("set")); // set 操作增加增量插件支持 - this.incrementsSupport(eleUpsertByExampleWithBLOBs, XmlElementGeneratorTools.generateSets(columns, "record."), introspectedTable, true); + if (incTools.support()) { + for (Element ele : incTools.generateSets(columns, "record.", false)) { + eleUpsertByExampleWithBLOBs.addElement(ele); + } + } else { + for (Element ele : XmlElementGeneratorTools.generateSets(columns, "record.")) { + eleUpsertByExampleWithBLOBs.addElement(ele); + } + } // update where eleUpsertByExampleWithBLOBs.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -531,6 +596,7 @@ public class UpsertPlugin extends BasePlugin { */ private void generateXmlElementWithoutBLOBs(Document document, IntrospectedTable introspectedTable) { List columns = ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getNonBLOBColumns()); + IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings); // ====================================== upsert ====================================== XmlElement eleUpsert = new XmlElement("insert"); @@ -555,8 +621,15 @@ public class UpsertPlugin extends BasePlugin { } eleUpsert.addElement(new TextElement("on duplicate key update ")); // set 操作增加增量插件支持 - this.incrementsSupport(eleUpsert, XmlElementGeneratorTools.generateSets(columns), introspectedTable, false); - + if (incTools.support()) { + for (Element ele : incTools.generateSets(columns, null, false)) { + eleUpsert.addElement(ele); + } + } else { + for (Element ele : XmlElementGeneratorTools.generateSets(columns)) { + eleUpsert.addElement(ele); + } + } document.getRootElement().addElement(eleUpsert); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。"); @@ -587,7 +660,15 @@ public class UpsertPlugin extends BasePlugin { eleUpsertByExample.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); eleUpsertByExample.addElement(new TextElement("set")); // set 操作增加增量插件支持 - this.incrementsSupport(eleUpsertByExample, XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record."), introspectedTable, true); + if (incTools.support()) { + for (Element ele : incTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record.", false)) { + eleUpsertByExample.addElement(ele); + } + } else { + for (Element ele : XmlElementGeneratorTools.generateSets(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(columns), "record.")) { + eleUpsertByExample.addElement(ele); + } + } // update where eleUpsertByExample.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); @@ -608,13 +689,13 @@ public class UpsertPlugin extends BasePlugin { private void generateExistsClause(IntrospectedTable introspectedTable, XmlElement element, boolean selective, List columns) { element.addElement(new TextElement("select")); if (selective) { - if (this.withSelectiveEnhancedPlugin){ + if (this.withSelectiveEnhancedPlugin) { // selective XmlElement chooseEle = new XmlElement("choose"); element.addElement(chooseEle); XmlElement selectWhenEle = new XmlElement("when"); - selectWhenEle.addAttribute(new Attribute("test", "selective.length > 0")); + selectWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); chooseEle.addElement(selectWhenEle); XmlElement valuesForeachEle = new XmlElement("foreach"); @@ -653,56 +734,4 @@ 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, warnings); - 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]; - IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, 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, warnings); - for (TextElement element : elements) { - if (incTools.support()) { - // 获取column - String text = element.getContent().trim(); - 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; - } - } - 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 index 22e3124..8cda224 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/utils/IncrementsPluginTools.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/utils/IncrementsPluginTools.java @@ -32,6 +32,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; /** @@ -125,13 +126,85 @@ public class IncrementsPluginTools { return false; } + /** + * 生成sets Selective Ele + * @param columns + * @param prefix + * @param bracket + * @return + */ + public XmlElement generateSetsSelective(List columns, String prefix, boolean bracket) { + XmlElement eleTrim = new XmlElement("trim"); + if (bracket) { + eleTrim.addAttribute(new Attribute("prefix", "(")); + eleTrim.addAttribute(new Attribute("suffix", ")")); + eleTrim.addAttribute(new Attribute("suffixOverrides", ",")); + } else { + eleTrim.addAttribute(new Attribute("suffixOverrides", ",")); + } + + for (IntrospectedColumn introspectedColumn : columns) { + XmlElement eleIf = new XmlElement("if"); + eleIf.addAttribute(new Attribute("test", introspectedColumn.getJavaProperty(prefix) + " != null")); + if (this.supportColumn(introspectedColumn)) { + for (Element ele : this.generatedIncrementsElement(introspectedColumn, prefix, true)) { + eleIf.addElement(ele); + } + } else { + eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = " + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ",")); + } + eleTrim.addElement(eleIf); + } + + return eleTrim; + } + + /** + * 生成sets Ele + * @param columns + * @param prefix + * @param bracket + * @return + */ + public List generateSets(List columns, String prefix, boolean bracket) { + List list = new ArrayList<>(); + if (bracket) { + list.add(new TextElement("(")); + } + Iterator columnIterator = columns.iterator(); + while (columnIterator.hasNext()) { + IntrospectedColumn introspectedColumn = columnIterator.next(); + + if (this.supportColumn(introspectedColumn)) { + list.add(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = ")); + for (Element ele : this.generatedIncrementsElement(introspectedColumn, prefix, columnIterator.hasNext())) { + list.add(ele); + } + } else { + StringBuilder sb = new StringBuilder(); + sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)); + sb.append(" = "); + sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix)); + if (columnIterator.hasNext()) { + sb.append(", "); + } + list.add(new TextElement(sb.toString())); + } + } + if (bracket) { + list.add(new TextElement(")")); + } + + return list; + } + /** * 生成增量操作节点 * @param introspectedColumn - * @param hasPrefix + * @param prefix * @param hasComma */ - public List generatedIncrementsElement(IntrospectedColumn introspectedColumn, boolean hasPrefix, boolean hasComma) { + public List generatedIncrementsElement(IntrospectedColumn introspectedColumn, String prefix, boolean hasComma) { List list = new ArrayList<>(); // 1. column = 节点 @@ -145,20 +218,20 @@ public class IncrementsPluginTools { XmlElement when = new XmlElement("when"); when.addAttribute(new Attribute( "test", - (hasPrefix ? "record." : "_parameter.") + IncrementsPlugin.METHOD_INC_CHECK + (prefix != null ? prefix : "_parameter.") + IncrementsPlugin.METHOD_INC_CHECK + "('" + MyBatis3FormattingUtilities.escapeStringForMyBatis3(introspectedColumn.getActualColumnName()) + "')" )); TextElement spec = new TextElement( MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) - + " ${" + (hasPrefix ? "record." : "") + + " ${" + (prefix != null ? prefix : "") + IncrementsPlugin.FIELD_INC_MAP + "." + MyBatis3FormattingUtilities.escapeStringForMyBatis3(introspectedColumn.getActualColumnName()) + ".value} " - + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null)); + + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix)); when.addElement(spec); choose.addElement(when); // 启用了增量操作 XmlElement otherwise = new XmlElement("otherwise"); - TextElement normal = new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null)); + TextElement normal = new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix)); otherwise.addElement(normal); choose.addElement(otherwise); @@ -171,4 +244,36 @@ public class IncrementsPluginTools { return list; } + + /** + * 创建 sets (SelectiveEnhancedPlugin) + * @param setForeachEle + */ + public void generateSetsSelectiveWithSelectiveEnhancedPlugin(XmlElement setForeachEle) { + XmlElement choose = new XmlElement("choose"); + + for (IntrospectedColumn introspectedColumn : columns) { + XmlElement when = new XmlElement("when"); + + // 需要 inc 的列 + StringBuilder sb = new StringBuilder(); + sb.append("'"); + sb.append(introspectedColumn.getActualColumnName()); + sb.append("'.toString()"); + sb.append(" == "); + sb.append("column.value"); + + when.addAttribute(new Attribute("test", sb.toString())); + when.addElement(new TextElement("${column.value} = ${column.value} ${record.incrementsColumnsInfoMap." + + introspectedColumn.getActualColumnName() + + ".value} #{record.${column.javaProperty},jdbcType=${column.jdbcType}}")); + choose.addElement(when); + } + + XmlElement otherwise = new XmlElement("otherwise"); + otherwise.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}")); + choose.addElement(otherwise); + + setForeachEle.addElement(choose); + } } diff --git a/src/test/java/com/itfsw/mybatis/generator/plugins/IncrementsPluginTest.java b/src/test/java/com/itfsw/mybatis/generator/plugins/IncrementsPluginTest.java index 6dbf4c0..d172140 100644 --- a/src/test/java/com/itfsw/mybatis/generator/plugins/IncrementsPluginTest.java +++ b/src/test/java/com/itfsw/mybatis/generator/plugins/IncrementsPluginTest.java @@ -19,12 +19,13 @@ package com.itfsw.mybatis.generator.plugins; import com.itfsw.mybatis.generator.plugins.tools.*; import org.apache.ibatis.session.SqlSession; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import java.io.IOException; +import java.lang.reflect.Array; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; @@ -44,8 +45,8 @@ public class IncrementsPluginTest { /** * 初始化数据库 */ - @BeforeClass - public static void init() throws Exception { + @Before + public void init() throws Exception { DBHelper.createDB("scripts/IncrementsPlugin/init.sql"); } @@ -211,6 +212,99 @@ public class IncrementsPluginTest { }); } + /** + * 测试整合 SelectiveEnhancedPlugin 插件 + */ + @Test + public void testWithSelectiveEnhancedPlugin() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException { + MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-selective-enhanced-plugin.xml"); + tool.generate(new AbstractShellCallback() { + @Override + public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { + // 1. 测试updateByExampleSelective + ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); + + ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample"); + ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria")); + criteria.invoke("andIdEqualTo", 3l); + + ObjectUtil tbBuilder = new ObjectUtil(loader, packagz + ".Tb$Builder"); + ObjectUtil tbBuilderInc = new ObjectUtil(loader, packagz + ".Tb$Builder$Inc#INC"); + tbBuilder.invoke("incF1", 100l, tbBuilderInc.getObject()); + tbBuilder.invoke("incF2", 200l); + + + // selective + ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1"); + ObjectUtil TbColumnIncF1 = new ObjectUtil(loader, packagz + ".Tb$Column#incF1"); + ObjectUtil TbColumnIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#incF2"); + Object columns = Array.newInstance(TbColumnField1.getCls(), 3); + Array.set(columns, 0, TbColumnField1.getObject()); + Array.set(columns, 1, TbColumnIncF1.getObject()); + Array.set(columns, 2, TbColumnIncF2.getObject()); + + // sql + // 非空判断 + String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject()); + Assert.assertEquals(sql, "update tb SET inc_f1 = inc_f1 + 100 , inc_f2 = 200 WHERE ( id = '3' )"); + // selective 指定 + sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject(), columns); + Assert.assertEquals(sql, "update tb SET field1 = 'null' , inc_f1 = inc_f1 + 100 , inc_f2 = 200 WHERE ( id = '3' )"); + // 执行 + // inc_f1 增加100 + Object result = tbMapper.invoke("updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject(), columns); + Assert.assertEquals(result, 1); + ResultSet rs = DBHelper.execute(sqlSession.getConnection(), "select inc_f1 from tb where id = 3"); + rs.first(); + Assert.assertEquals(rs.getInt("inc_f1"), 103); + + // inc_f1 再减去50 + ObjectUtil tbBuilderDec = new ObjectUtil(loader, packagz + ".Tb$Builder$Inc#DEC"); + tbBuilder.invoke("incF1", 50l, tbBuilderDec.getObject()); + result = tbMapper.invoke("updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject(), Array.newInstance(TbColumnField1.getCls(), 0)); + Assert.assertEquals(result, 1); + // 验证执行结果 + rs = DBHelper.execute(sqlSession.getConnection(), "select inc_f1 from tb where id = 3"); + rs.first(); + Assert.assertEquals(rs.getInt("inc_f1"), 53); + + + // 2. 测试updateByPrimaryKeySelective + ObjectUtil tbKeysMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbKeysMapper"))); + + ObjectUtil tbKeysBuilderInc = new ObjectUtil(loader, packagz + ".TbKeys$Builder$Inc#INC"); + + ObjectUtil tbKeysBuilder = new ObjectUtil(loader, packagz + ".TbKeys$Builder"); + tbKeysBuilder.invoke("key1", 1l); + tbKeysBuilder.invoke("key2", "k1"); + tbKeysBuilder.invoke("incF1", 10l, tbKeysBuilderInc.getObject()); + tbKeysBuilder.invoke("incF3", 30l, tbKeysBuilderInc.getObject()); + + // selective + ObjectUtil TbColumnKey1 = new ObjectUtil(loader, packagz + ".TbKeys$Column#key1"); + TbColumnIncF1 = new ObjectUtil(loader, packagz + ".TbKeys$Column#incF1"); + columns = Array.newInstance(TbColumnKey1.getCls(), 2); + Array.set(columns, 0, TbColumnKey1.getObject()); + Array.set(columns, 1, TbColumnIncF1.getObject()); + + // sql + // 非空判断 + sql = SqlHelper.getFormatMapperSql(tbKeysMapper.getObject(), "updateByPrimaryKeySelective", tbKeysBuilder.invoke("build")); + Assert.assertEquals(sql, "update tb_keys SET inc_f1 = inc_f1 + 10 , inc_f3 = inc_f3 + 30 where key1 = 1 and key2 = 'k1'"); + // selective 指定 + sql = SqlHelper.getFormatMapperSql(tbKeysMapper.getObject(), "updateByPrimaryKeySelective", tbKeysBuilder.invoke("build"), columns); + Assert.assertEquals(sql, "update tb_keys SET key1 = 1 , inc_f1 = inc_f1 + 10 where key1 = 1 and key2 = 'k1'"); + // 执行 + result = tbKeysMapper.invoke("updateByPrimaryKeySelective", tbKeysBuilder.invoke("build"), columns); + Assert.assertEquals(result, 1); + // 验证执行结果 + rs = DBHelper.execute(sqlSession.getConnection(), "select inc_f1, inc_f3 from tb_keys where key1 = 1 and key2 = 'k1'"); + rs.first(); + Assert.assertEquals(rs.getInt("inc_f1"), 11); + } + }); + } + /** * 测试 autoDelimitKeywords */ diff --git a/src/test/java/com/itfsw/mybatis/generator/plugins/OldSelectiveEnhancedPluginTest.java b/src/test/java/com/itfsw/mybatis/generator/plugins/OldSelectiveEnhancedPluginTest.java index 8fc355a..0a3f305 100644 --- a/src/test/java/com/itfsw/mybatis/generator/plugins/OldSelectiveEnhancedPluginTest.java +++ b/src/test/java/com/itfsw/mybatis/generator/plugins/OldSelectiveEnhancedPluginTest.java @@ -212,7 +212,7 @@ public class OldSelectiveEnhancedPluginTest { // sql String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertSelective", tb.getObject()); - Assert.assertEquals(sql, "insert into tb ( id, field_1, inc_f2 ) values ( 10, 'null', 5 ) on duplicate key update id = 10, field_1 = 'null', inc_f2 = 5"); + Assert.assertEquals(sql, "insert into tb ( id, field_1, inc_f2 ) values ( 10, 'null', 5 ) on duplicate key update field_1 = 'null', inc_f2 = 5"); Object result = tbMapper.invoke("upsertSelective", tb.getObject()); Assert.assertEquals(result, 1); } diff --git a/src/test/java/com/itfsw/mybatis/generator/plugins/UpsertPluginTest.java b/src/test/java/com/itfsw/mybatis/generator/plugins/UpsertPluginTest.java index 4d72484..c2321e4 100644 --- a/src/test/java/com/itfsw/mybatis/generator/plugins/UpsertPluginTest.java +++ b/src/test/java/com/itfsw/mybatis/generator/plugins/UpsertPluginTest.java @@ -165,7 +165,7 @@ public class UpsertPluginTest { // sql String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertSelective", tb.getObject()); - Assert.assertEquals(sql, "insert into tb ( id, field1 ) values ( 20, 'ts1' ) on duplicate key update id = 20, field1 = 'ts1'"); + Assert.assertEquals(sql, "insert into tb ( id, field1 ) values ( 20, 'ts1' ) on duplicate key update field1 = 'ts1'"); Object result = tbMapper.invoke("upsertSelective", tb.getObject()); Assert.assertEquals(result, 1); @@ -179,7 +179,7 @@ public class UpsertPluginTest { // sql sql = SqlHelper.getFormatMapperSql(TbBlobsMapper.getObject(), "upsertSelective", TbBlobsWithBLOBs.getObject()); - Assert.assertEquals(sql, "insert into tb_blobs ( id, field1, field2 ) values ( 500, 'ts1', 'ts2' ) on duplicate key update id = 500, field1 = 'ts1', field2 = 'ts2'"); + Assert.assertEquals(sql, "insert into tb_blobs ( id, field1, field2 ) values ( 500, 'ts1', 'ts2' ) on duplicate key update field1 = 'ts1', field2 = 'ts2'"); result = TbBlobsMapper.invoke("upsertSelective", TbBlobsWithBLOBs.getObject()); Assert.assertEquals(result, 1); } diff --git a/src/test/resources/scripts/IncrementsPlugin/mybatis-generator-with-selective-enhanced-plugin.xml b/src/test/resources/scripts/IncrementsPlugin/mybatis-generator-with-selective-enhanced-plugin.xml new file mode 100644 index 0000000..650fd8a --- /dev/null +++ b/src/test/resources/scripts/IncrementsPlugin/mybatis-generator-with-selective-enhanced-plugin.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+ + +
+
+
\ No newline at end of file