Commit a8a788f1 authored by hewei's avatar hewei

重新整合 IncrementsPlugin 插件

parent a8c0a38a
......@@ -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;
}
......
......@@ -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", ","));
// 自增插件支持
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");
// 自增插件支持
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", ","));
// 自增插件支持
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");
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."
));
setChooseEle.addElement(setOtherwiseEle);
}
XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(answer, introspectedTable.getPrimaryKeyColumns(), "record.");
......
......@@ -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<IntrospectedColumn> 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");
// set 操作增加增量插件支持
if (incTools.support()) {
setOtherwiseEle.addElement(incTools.generateSetsSelective(
ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()),
"record.",
false
));
} else {
setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective(
ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()),
"record."
"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<IntrospectedColumn> 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<IntrospectedColumn> 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<IntrospectedColumn> 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<Element> 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<TextElement> 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
......@@ -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<IntrospectedColumn> 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<Element> generateSets(List<IntrospectedColumn> columns, String prefix, boolean bracket) {
List<Element> list = new ArrayList<>();
if (bracket) {
list.add(new TextElement("("));
}
Iterator<IntrospectedColumn> 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<Element> generatedIncrementsElement(IntrospectedColumn introspectedColumn, boolean hasPrefix, boolean hasComma) {
public List<Element> generatedIncrementsElement(IntrospectedColumn introspectedColumn, String prefix, boolean hasComma) {
List<Element> 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);
}
}
......@@ -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
*/
......
......@@ -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);
}
......
......@@ -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);
}
......
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018.
~
~ 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">
<!-- 插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.IncrementsPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--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">
<property name="incrementsColumns" value="inc_f1"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys">
<property name="incrementsColumns" value=" inc_f1, inc_f2, inc_f3 "/>
</table>
<table tableName="tb_blobs">
<property name="incrementsColumns" value="inc_f1,inc_f3"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment