Commit c33616c4 authored by hewei's avatar hewei

重构代码插件依赖关系

parent cbfe10c9
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.IntrospectedTableTools;
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.*;
import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ---------------------------------------------------------------------------
* Selective 增强插件
* ---------------------------------------------------------------------------
*
* @author: hewei
* @time:2017/4/20 15:39
* ---------------------------------------------------------------------------
*/
@Deprecated
public class OldSelectiveEnhancedPlugin extends BasePlugin {
public static final String METHOD_HAS_SELECTIVE = "hasSelective"; // 方法名
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是使用了ModelColumnPlugin插件
if (!PluginTools.checkDependencyPlugin(getContext(), ModelColumnPlugin.class)) {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
return false;
}
// 插件位置
PluginTools.shouldAfterPlugins(getContext(), this.getClass(), warnings, UpsertPlugin.class);
return super.validate(warnings);
}
/**
* Model Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// import
topLevelClass.addImportedType(FullyQualifiedJavaType.getNewMapInstance());
topLevelClass.addImportedType(FullyQualifiedJavaType.getNewHashMapInstance());
// field
Field selectiveColumnsField = new Field("selectiveColumns", new FullyQualifiedJavaType("Map<String, Boolean>"));
commentGenerator.addFieldComment(selectiveColumnsField, introspectedTable);
selectiveColumnsField.setVisibility(JavaVisibility.PRIVATE);
selectiveColumnsField.setInitializationString("new HashMap<String, Boolean>()");
topLevelClass.addField(selectiveColumnsField);
// Method hasSelective
Method mHasSelective = new Method(METHOD_HAS_SELECTIVE);
commentGenerator.addGeneralMethodComment(mHasSelective, introspectedTable);
mHasSelective.setVisibility(JavaVisibility.PUBLIC);
mHasSelective.setReturnType(FullyQualifiedJavaType.getBooleanPrimitiveInstance());
mHasSelective.addBodyLine("return this.selectiveColumns.size() > 0;");
topLevelClass.addMethod(mHasSelective);
// Method hasSelective
Method mHasSelective1 = new Method(METHOD_HAS_SELECTIVE);
commentGenerator.addGeneralMethodComment(mHasSelective1, introspectedTable);
mHasSelective1.setVisibility(JavaVisibility.PUBLIC);
mHasSelective1.setReturnType(FullyQualifiedJavaType.getBooleanPrimitiveInstance());
mHasSelective1.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "column"));
mHasSelective1.addBodyLine("return this.selectiveColumns.get(column) != null;");
topLevelClass.addMethod(mHasSelective1);
// Method selective
Method mSelective = new Method("selective");
commentGenerator.addGeneralMethodComment(mSelective, introspectedTable);
mSelective.setVisibility(JavaVisibility.PUBLIC);
mSelective.setReturnType(topLevelClass.getType());
mSelective.addParameter(new Parameter(new FullyQualifiedJavaType(ModelColumnPlugin.ENUM_NAME), "columns", true));
mSelective.addBodyLine("this.selectiveColumns.clear();");
mSelective.addBodyLine("if (columns != null) {");
mSelective.addBodyLine("for (" + ModelColumnPlugin.ENUM_NAME + " column : columns) {");
mSelective.addBodyLine("this.selectiveColumns.put(column.value(), true);");
mSelective.addBodyLine("}");
mSelective.addBodyLine("}");
mSelective.addBodyLine("return this;");
topLevelClass.addMethod(mSelective);
return true;
}
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param document
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
List<Element> rootElements = document.getRootElement().getElements();
for (Element rootElement : rootElements) {
if (rootElement instanceof XmlElement) {
XmlElement xmlElement = (XmlElement) rootElement;
List<Attribute> attributes = xmlElement.getAttributes();
// 查找ID
String id = "";
for (Attribute attribute : attributes) {
if (attribute.getName().equals("id")) {
id = attribute.getValue();
}
}
// ====================================== 1. insertSelective ======================================
if ("insertSelective".equals(id)) {
List<XmlElement> eles = XmlElementGeneratorTools.findXmlElements(xmlElement, "trim");
for (XmlElement ele : eles) {
this.replaceEle(ele, "_parameter.", introspectedTable);
}
}
// ====================================== 2. updateByExampleSelective ======================================
if ("updateByExampleSelective".equals(id)) {
List<XmlElement> eles = XmlElementGeneratorTools.findXmlElements(xmlElement, "set");
for (XmlElement ele : eles) {
this.replaceEle(ele, "record.", introspectedTable);
}
}
// ====================================== 3. updateByPrimaryKeySelective ======================================
if ("updateByPrimaryKeySelective".equals(id)) {
List<XmlElement> eles = XmlElementGeneratorTools.findXmlElements(xmlElement, "set");
for (XmlElement ele : eles) {
this.replaceEle(ele, "_parameter.", introspectedTable);
}
}
// ====================================== 4. upsertSelective ======================================
if ("upsertSelective".equals(id)) {
List<XmlElement> eles = XmlElementGeneratorTools.findXmlElements(xmlElement, "trim");
for (XmlElement ele : eles) {
this.replaceEle(ele, "_parameter.", introspectedTable);
}
}
// ====================================== 5. upsertByExampleSelective ======================================
if ("upsertByExampleSelective".equals(id)) {
List<XmlElement> eles = XmlElementGeneratorTools.findXmlElements(xmlElement, "trim");
this.replaceEle(eles.get(1), "record.", introspectedTable);
// upsertByExampleSelective的第二个trim比较特殊,需另行处理
this.replaceEleForUpsertByExampleSelective(eles.get(2), "record.", introspectedTable, !introspectedTable.getRules().generateRecordWithBLOBsClass());
List<XmlElement> eles1 = XmlElementGeneratorTools.findXmlElements(xmlElement, "set");
for (XmlElement ele : eles1) {
this.replaceEle(ele, "record.", introspectedTable);
}
}
}
}
return true;
}
/**
* 替换节点if信息
*
* @param element
* @param prefix
* @param introspectedTable
*/
private void replaceEle(XmlElement element, String prefix, IntrospectedTable introspectedTable) {
// choose
XmlElement chooseEle = new XmlElement("choose");
// when
XmlElement whenEle = new XmlElement("when");
whenEle.addAttribute(new Attribute("test", prefix + METHOD_HAS_SELECTIVE + "()"));
for (Element ele : element.getElements()) {
// 对于字符串主键,是没有if判断节点的
if (ele instanceof XmlElement) {
// if的text节点
XmlElement xmlElement = (XmlElement) ele;
// 找出field 名称
String text = ((TextElement) xmlElement.getElements().get(0)).getContent();
String columnName = "";
if (text.matches("#\\{.*\\},?")) {
Pattern pattern = Pattern.compile("#\\{(.*?),.*\\},?");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
String field = matcher.group(1);
// 查找对应column
for (IntrospectedColumn column : introspectedTable.getAllColumns()) {
if (column.getJavaProperty().equals(field)) {
columnName = column.getActualColumnName();
}
}
}
} else {
if (text.matches(".*=.*")) {
columnName = text.split("=")[0];
} else {
columnName = text.replaceAll(",", "");
}
// bug fixed: 修正使用autoDelimitKeywords过滤关键词造成的field前后加了特殊字符的问题
// columnName = columnName.trim().replaceAll("`", "").replaceAll("\"", "").replaceAll("'", "");
}
IntrospectedColumn column = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
XmlElement ifEle = new XmlElement("if");
ifEle.addAttribute(new Attribute("test", prefix + METHOD_HAS_SELECTIVE + "(\'" + column.getActualColumnName() + "\')"));
for (Element ifChild : xmlElement.getElements()) {
ifEle.addElement(ifChild);
}
whenEle.addElement(ifEle);
} else {
whenEle.addElement(ele);
}
}
// otherwise
XmlElement otherwiseEle = new XmlElement("otherwise");
for (Element ele : element.getElements()) {
otherwiseEle.addElement(ele);
}
chooseEle.addElement(whenEle);
chooseEle.addElement(otherwiseEle);
// 清空原始节点,新增choose节点
element.getElements().clear();
element.addElement(chooseEle);
}
/**
* 替换节点upsertByExampleSelective if信息
*
* @param element
* @param prefix
* @param introspectedTable
* @param allColumns
*/
private void replaceEleForUpsertByExampleSelective(XmlElement element, String prefix, IntrospectedTable introspectedTable, boolean allColumns) {
// choose
XmlElement chooseEle = new XmlElement("choose");
// when
XmlElement whenEle = new XmlElement("when");
whenEle.addAttribute(new Attribute("test", prefix + METHOD_HAS_SELECTIVE + "()"));
for (IntrospectedColumn introspectedColumn : (allColumns ? introspectedTable.getAllColumns() : introspectedTable.getNonBLOBColumns())) {
XmlElement eleIf = new XmlElement("if");
eleIf.addAttribute(new Attribute("test", prefix + METHOD_HAS_SELECTIVE + "(\'" + introspectedColumn.getActualColumnName() + "\')"));
eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
whenEle.addElement(eleIf);
}
// otherwise
XmlElement otherwiseEle = new XmlElement("otherwise");
for (Element ele : element.getElements()) {
otherwiseEle.addElement(ele);
}
chooseEle.addElement(whenEle);
chooseEle.addElement(otherwiseEle);
// 清空原始节点,新增choose节点
element.getElements().clear();
element.addElement(chooseEle);
}
}
/*
* 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.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 乐观锁插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/4/26 10:24
* ---------------------------------------------------------------------------
*/
public class OptimisticLockerPlugin extends BasePlugin {
@Override
public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
return super.contextGenerateAdditionalJavaFiles(introspectedTable);
}
}
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
package com.itfsw.mybatis.generator.plugins; package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin; 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.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools; import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.hook.IUpsertPluginHook;
import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
...@@ -42,7 +42,7 @@ import java.util.List; ...@@ -42,7 +42,7 @@ import java.util.List;
* @time:2018/4/20 15:39 * @time:2018/4/20 15:39
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
*/ */
public class SelectiveEnhancedPlugin extends BasePlugin { public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPluginHook {
/** /**
* {@inheritDoc} * {@inheritDoc}
...@@ -56,12 +56,6 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -56,12 +56,6 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
return false; return false;
} }
// 和 OldSelectiveEnhancedPlugin 不能同时使用
if (PluginTools.checkDependencyPlugin(getContext(), OldSelectiveEnhancedPlugin.class)) {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "不能和" + OldSelectiveEnhancedPlugin.class.getTypeName() + "插件同时使用!");
return false;
}
return super.validate(warnings); return super.validate(warnings);
} }
...@@ -164,12 +158,8 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -164,12 +158,8 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
@Override @Override
public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
// 清空 // 清空
XmlElement answer = element; XmlElement answer = new XmlElement("insert");
answer.getElements().clear();
answer.getAttributes().clear();
answer.addAttribute(new Attribute("id", introspectedTable.getInsertSelectiveStatementId())); answer.addAttribute(new Attribute("id", introspectedTable.getInsertSelectiveStatementId()));
answer.addAttribute(new Attribute("parameterType", "map")); answer.addAttribute(new Attribute("parameterType", "map"));
commentGenerator.addComment(answer); commentGenerator.addComment(answer);
...@@ -196,65 +186,13 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -196,65 +186,13 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime()); sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
answer.addElement(new TextElement(sb.toString())); answer.addElement(new TextElement(sb.toString()));
// selective // columns
XmlElement insertChooseEle = new XmlElement("choose"); answer.addElement(this.generateInsertColumnSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())));
answer.addElement(insertChooseEle); // values
answer.addElement(new TextElement("values"));
XmlElement insertWhenEle = new XmlElement("when"); answer.addElement(this.generateInsertValuesSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())));
insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
insertChooseEle.addElement(insertWhenEle);
XmlElement insertForeachEle = new XmlElement("foreach");
insertForeachEle.addAttribute(new Attribute("collection", "selective"));
insertForeachEle.addAttribute(new Attribute("item", "column"));
insertForeachEle.addAttribute(new Attribute("open", "("));
insertForeachEle.addAttribute(new Attribute("separator", ","));
insertForeachEle.addAttribute(new Attribute("close", ")"));
insertForeachEle.addElement(new TextElement("${column.value}"));
insertWhenEle.addElement(insertForeachEle);
XmlElement insertOtherwiseEle = new XmlElement("otherwise");
insertOtherwiseEle.addElement(XmlElementGeneratorTools.generateKeysSelective(
ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()),
"record."
));
insertChooseEle.addElement(insertOtherwiseEle);
XmlElement insertTrimElement = new XmlElement("trim");
insertTrimElement.addAttribute(new Attribute("prefix", "("));
insertTrimElement.addAttribute(new Attribute("suffix", ")"));
insertTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
insertOtherwiseEle.addElement(insertTrimElement);
XmlElement valuesChooseEle = new XmlElement("choose");
answer.addElement(valuesChooseEle);
XmlElement valuesWhenEle = new XmlElement("when");
valuesWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
valuesChooseEle.addElement(valuesWhenEle);
XmlElement valuesForeachEle = new XmlElement("foreach");
valuesForeachEle.addAttribute(new Attribute("collection", "selective"));
valuesForeachEle.addAttribute(new Attribute("item", "column"));
valuesForeachEle.addAttribute(new Attribute("open", "values ("));
valuesForeachEle.addAttribute(new Attribute("separator", ","));
valuesForeachEle.addAttribute(new Attribute("close", ")"));
valuesForeachEle.addElement(new TextElement("#{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
valuesWhenEle.addElement(valuesForeachEle);
XmlElement valuesOtherwiseEle = new XmlElement("otherwise"); XmlElementGeneratorTools.replaceXmlElement(element, answer);
valuesOtherwiseEle.addElement(XmlElementGeneratorTools.generateValuesSelective(
ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()),
"record."
));
valuesChooseEle.addElement(valuesOtherwiseEle);
XmlElement valuesTrimElement = new XmlElement("trim");
valuesTrimElement.addAttribute(new Attribute("prefix", "values ("));
valuesTrimElement.addAttribute(new Attribute("suffix", ")"));
valuesTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
valuesOtherwiseEle.addElement(valuesTrimElement);
return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable); return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable);
} }
...@@ -268,12 +206,8 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -268,12 +206,8 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
*/ */
@Override @Override
public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
// 清空 // 清空
XmlElement answer = element; XmlElement answer = new XmlElement("update");
answer.getElements().clear();
answer.getAttributes().clear();
answer.addAttribute(new Attribute("id", introspectedTable.getUpdateByExampleSelectiveStatementId())); answer.addAttribute(new Attribute("id", introspectedTable.getUpdateByExampleSelectiveStatementId()));
answer.addAttribute(new Attribute("parameterType", "map")); answer.addAttribute(new Attribute("parameterType", "map"));
...@@ -286,46 +220,12 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -286,46 +220,12 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
// selective // selective
answer.addElement(new TextElement("SET")); answer.addElement(new TextElement("SET"));
XmlElement setChooseEle = new XmlElement("choose"); answer.addElement(this.generateSetsSelective(ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns())));
answer.addElement(setChooseEle);
XmlElement setWhenEle = new XmlElement("when");
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("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)); answer.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
XmlElementGeneratorTools.replaceXmlElement(element, answer);
return super.sqlMapUpdateByExampleSelectiveElementGenerated(element, introspectedTable); return super.sqlMapUpdateByExampleSelectiveElementGenerated(element, introspectedTable);
} }
...@@ -338,12 +238,8 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -338,12 +238,8 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
*/ */
@Override @Override
public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
// 清空 // 清空
XmlElement answer = element; XmlElement answer = new XmlElement("update");
answer.getElements().clear();
answer.getAttributes().clear();
answer.addAttribute(new Attribute("id", introspectedTable.getUpdateByPrimaryKeySelectiveStatementId())); answer.addAttribute(new Attribute("id", introspectedTable.getUpdateByPrimaryKeySelectiveStatementId()));
answer.addAttribute(new Attribute("parameterType", "map")); answer.addAttribute(new Attribute("parameterType", "map"));
...@@ -357,44 +253,182 @@ public class SelectiveEnhancedPlugin extends BasePlugin { ...@@ -357,44 +253,182 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
// selective // selective
answer.addElement(new TextElement("SET")); answer.addElement(new TextElement("SET"));
XmlElement setChooseEle = new XmlElement("choose"); answer.addElement(this.generateSetsSelective(ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns())));
answer.addElement(setChooseEle);
XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(answer, introspectedTable.getPrimaryKeyColumns(), "record.");
XmlElementGeneratorTools.replaceXmlElement(element, answer);
return super.sqlMapUpdateByPrimaryKeySelectiveElementGenerated(element, introspectedTable);
}
// =============================================== IUpsertPluginHook ===================================================
/**
* upsertSelective 方法
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
@Override
public boolean clientUpsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
// @Param("record")
method.getParameters().get(0).addAnnotation("@Param(\"record\")");
// column枚举
// 找出全字段对应的Model
FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
return true;
}
/**
* upsertByExampleSelective 方法
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
@Override
public boolean clientUpsertByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
// column枚举
// 找出全字段对应的Model
FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
return true;
}
/**
* upsertSelective xml
* @param element
* @param columns
* @param insertColumnsEle
* @param insertValuesEle
* @param setsEle
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
// parameterType
XmlElementGeneratorTools.replaceAttribute(element, new Attribute("parameterType", "map"));
// 替换insert column
XmlElementGeneratorTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns));
// 替换insert values
XmlElementGeneratorTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns));
// 替换update set
XmlElementGeneratorTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns));
return true;
}
/**
* upsertByExampleSelective xml
* @param element
* @param columns
* @param insertColumnsEle
* @param insertValuesEle
* @param setsEle
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
return false;
}
// ====================================================== 一些私有节点生成方法 =========================================================
/**
* insert column selective
* @param columns
* @return
*/
private XmlElement generateInsertColumnSelective(List<IntrospectedColumn> columns) {
XmlElement insertColumnsChooseEle = new XmlElement("choose");
XmlElement insertWhenEle = new XmlElement("when");
insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
insertColumnsChooseEle.addElement(insertWhenEle);
XmlElement insertForeachEle = new XmlElement("foreach");
insertForeachEle.addAttribute(new Attribute("collection", "selective"));
insertForeachEle.addAttribute(new Attribute("item", "column"));
insertForeachEle.addAttribute(new Attribute("open", "("));
insertForeachEle.addAttribute(new Attribute("separator", ","));
insertForeachEle.addAttribute(new Attribute("close", ")"));
insertForeachEle.addElement(new TextElement("${column.value}"));
insertWhenEle.addElement(insertForeachEle);
XmlElement insertOtherwiseEle = new XmlElement("otherwise");
insertOtherwiseEle.addElement(XmlElementGeneratorTools.generateKeysSelective(columns, "record."));
insertColumnsChooseEle.addElement(insertOtherwiseEle);
XmlElement insertTrimElement = new XmlElement("trim");
insertTrimElement.addAttribute(new Attribute("prefix", "("));
insertTrimElement.addAttribute(new Attribute("suffix", ")"));
insertTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
insertOtherwiseEle.addElement(insertTrimElement);
return insertColumnsChooseEle;
}
/**
* insert column selective
* @param columns
* @return
*/
private XmlElement generateInsertValuesSelective(List<IntrospectedColumn> columns) {
XmlElement insertValuesChooseEle = new XmlElement("choose");
XmlElement valuesWhenEle = new XmlElement("when");
valuesWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
insertValuesChooseEle.addElement(valuesWhenEle);
XmlElement valuesForeachEle = new XmlElement("foreach");
valuesForeachEle.addAttribute(new Attribute("collection", "selective"));
valuesForeachEle.addAttribute(new Attribute("item", "column"));
valuesForeachEle.addAttribute(new Attribute("open", "("));
valuesForeachEle.addAttribute(new Attribute("separator", ","));
valuesForeachEle.addAttribute(new Attribute("close", ")"));
valuesForeachEle.addElement(new TextElement("#{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
valuesWhenEle.addElement(valuesForeachEle);
XmlElement valuesOtherwiseEle = new XmlElement("otherwise");
insertValuesChooseEle.addElement(valuesOtherwiseEle);
valuesOtherwiseEle.addElement(XmlElementGeneratorTools.generateValuesSelective(columns, "record."));
return insertValuesChooseEle;
}
/**
* sets selective
* @param columns
* @return
*/
private XmlElement generateSetsSelective(List<IntrospectedColumn> columns) {
XmlElement setsChooseEle = new XmlElement("choose");
XmlElement setWhenEle = new XmlElement("when"); XmlElement setWhenEle = new XmlElement("when");
setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0")); setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
setChooseEle.addElement(setWhenEle); setsChooseEle.addElement(setWhenEle);
XmlElement setForeachEle = new XmlElement("foreach"); XmlElement setForeachEle = new XmlElement("foreach");
setWhenEle.addElement(setForeachEle);
setForeachEle.addAttribute(new Attribute("collection", "selective")); setForeachEle.addAttribute(new Attribute("collection", "selective"));
setForeachEle.addAttribute(new Attribute("item", "column")); setForeachEle.addAttribute(new Attribute("item", "column"));
setForeachEle.addAttribute(new Attribute("separator", ",")); 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"); XmlElement setOtherwiseEle = new XmlElement("otherwise");
setChooseEle.addElement(setOtherwiseEle); setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective(columns, "record."));
// 自增插件支持 setsChooseEle.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."); return setsChooseEle;
return super.sqlMapUpdateByPrimaryKeySelectiveElementGenerated(element, introspectedTable);
} }
} }
...@@ -16,14 +16,16 @@ ...@@ -16,14 +16,16 @@
package com.itfsw.mybatis.generator.plugins; package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.*; import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.hook.IUpsertPluginHook;
import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.*; import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*; import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.mybatis3.ListUtilities; import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.internal.util.StringUtility; import org.mybatis.generator.internal.util.StringUtility;
import java.util.Arrays; import java.util.Arrays;
...@@ -50,7 +52,6 @@ public class UpsertPlugin extends BasePlugin { ...@@ -50,7 +52,6 @@ public class UpsertPlugin extends BasePlugin {
public static final String PRO_ALLOW_MULTI_QUERIES = "allowMultiQueries"; // property allowMultiQueries public static final String PRO_ALLOW_MULTI_QUERIES = "allowMultiQueries"; // property allowMultiQueries
private boolean allowMultiQueries = false; // 是否允许多sql提交 private boolean allowMultiQueries = false; // 是否允许多sql提交
private boolean withSelectiveEnhancedPlugin = false; // 是否启用了Selective增强插件
/** /**
* {@inheritDoc} * {@inheritDoc}
...@@ -73,9 +74,6 @@ public class UpsertPlugin extends BasePlugin { ...@@ -73,9 +74,6 @@ public class UpsertPlugin extends BasePlugin {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件您开启了allowMultiQueries支持,注意在jdbc url 配置中增加“allowMultiQueries=true”支持(不怎么建议使用该功能,开启多sql提交会增加sql注入的风险,请确保你所有sql都使用MyBatis书写,请不要使用statement进行sql提交)!"); warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件您开启了allowMultiQueries支持,注意在jdbc url 配置中增加“allowMultiQueries=true”支持(不怎么建议使用该功能,开启多sql提交会增加sql注入的风险,请确保你所有sql都使用MyBatis书写,请不要使用statement进行sql提交)!");
} }
// 是否启用了Selective增强插件
this.withSelectiveEnhancedPlugin = PluginTools.checkDependencyPlugin(context, SelectiveEnhancedPlugin.class);
return super.validate(warnings); return super.validate(warnings);
} }
...@@ -122,20 +120,16 @@ public class UpsertPlugin extends BasePlugin { ...@@ -122,20 +120,16 @@ public class UpsertPlugin extends BasePlugin {
Method mUpsertSelective = JavaElementGeneratorTools.generateMethod( Method mUpsertSelective = JavaElementGeneratorTools.generateMethod(
METHOD_UPSERT_SELECTIVE, METHOD_UPSERT_SELECTIVE,
JavaVisibility.DEFAULT, JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance() FullyQualifiedJavaType.getIntInstance(),
new Parameter(fullFieldModel, "record")
); );
if (withSelectiveEnhancedPlugin) {
mUpsertSelective.addParameter(new Parameter(fullFieldModel, "record", "@Param(\"record\")"));
// column枚举
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
mUpsertSelective.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
} else {
mUpsertSelective.addParameter(new Parameter(fullFieldModel, "record"));
}
commentGenerator.addGeneralMethodComment(mUpsertSelective, introspectedTable); commentGenerator.addGeneralMethodComment(mUpsertSelective, introspectedTable);
// interface 增加方法 // hook
interfaze.addMethod(mUpsertSelective); if (PluginTools.getHook(IUpsertPluginHook.class).clientUpsertSelectiveMethodGenerated(mUpsertSelective, interfaze, introspectedTable)) {
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertSelective方法。"); // interface 增加方法
interfaze.addMethod(mUpsertSelective);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertSelective方法。");
}
if (this.allowMultiQueries) { if (this.allowMultiQueries) {
// ====================================== upsertByExample ====================================== // ====================================== upsertByExample ======================================
...@@ -175,15 +169,13 @@ public class UpsertPlugin extends BasePlugin { ...@@ -175,15 +169,13 @@ public class UpsertPlugin extends BasePlugin {
new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record", "@Param(\"record\")"), new Parameter(introspectedTable.getRules().calculateAllFieldsClass(), "record", "@Param(\"record\")"),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")") new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")")
); );
if (withSelectiveEnhancedPlugin) {
// column枚举
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
mUpsertByExampleSelective.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
}
commentGenerator.addGeneralMethodComment(mUpsertByExampleSelective, introspectedTable); commentGenerator.addGeneralMethodComment(mUpsertByExampleSelective, introspectedTable);
// interface 增加方法 // hook
interfaze.addMethod(mUpsertByExampleSelective); if (PluginTools.getHook(IUpsertPluginHook.class).clientUpsertByExampleSelectiveMethodGenerated(mUpsertByExampleSelective, interfaze, introspectedTable)) {
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExampleSelective方法。"); // interface 增加方法
interfaze.addMethod(mUpsertByExampleSelective);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExampleSelective方法。");
}
} }
return super.clientGenerated(interfaze, topLevelClass, introspectedTable); return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
...@@ -215,239 +207,73 @@ public class UpsertPlugin extends BasePlugin { ...@@ -215,239 +207,73 @@ public class UpsertPlugin extends BasePlugin {
private void generateXmlElementWithSelective(Document document, IntrospectedTable introspectedTable) { private void generateXmlElementWithSelective(Document document, IntrospectedTable introspectedTable) {
List<IntrospectedColumn> columns = ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns()); List<IntrospectedColumn> columns = ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns());
if (withSelectiveEnhancedPlugin) { // ====================================== upsertSelective ======================================
// ====================================== upsertSelective ====================================== XmlElement insertEle = new XmlElement("insert");
XmlElement eleUpsertSelective = new XmlElement("insert"); insertEle.addAttribute(new Attribute("id", METHOD_UPSERT_SELECTIVE));
eleUpsertSelective.addAttribute(new Attribute("id", METHOD_UPSERT_SELECTIVE)); // 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
eleUpsertSelective.addAttribute(new Attribute("parameterType", "map")); commentGenerator.addComment(insertEle);
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(eleUpsertSelective);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertSelective, introspectedTable, "record.");
// insert // 参数类型
eleUpsertSelective.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime())); insertEle.addAttribute(new Attribute("parameterType", introspectedTable.getRules().calculateAllFieldsClass().getFullyQualifiedName()));
// selective
XmlElement insertChooseEle = new XmlElement("choose");
eleUpsertSelective.addElement(insertChooseEle);
XmlElement insertWhenEle = new XmlElement("when");
insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
insertChooseEle.addElement(insertWhenEle);
XmlElement insertForeachEle = new XmlElement("foreach");
insertForeachEle.addAttribute(new Attribute("collection", "selective"));
insertForeachEle.addAttribute(new Attribute("item", "column"));
insertForeachEle.addAttribute(new Attribute("open", "("));
insertForeachEle.addAttribute(new Attribute("separator", ","));
insertForeachEle.addAttribute(new Attribute("close", ")"));
insertForeachEle.addElement(new TextElement("${column.value}"));
insertWhenEle.addElement(insertForeachEle);
XmlElement insertOtherwiseEle = new XmlElement("otherwise");
insertOtherwiseEle.addElement(XmlElementGeneratorTools.generateKeysSelective(columns, "record."));
insertChooseEle.addElement(insertOtherwiseEle);
XmlElement insertTrimElement = new XmlElement("trim");
insertTrimElement.addAttribute(new Attribute("prefix", "("));
insertTrimElement.addAttribute(new Attribute("suffix", ")"));
insertTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
insertOtherwiseEle.addElement(insertTrimElement);
eleUpsertSelective.addElement(new TextElement("values"));
XmlElement valuesChooseEle = new XmlElement("choose");
eleUpsertSelective.addElement(valuesChooseEle);
XmlElement valuesWhenEle = new XmlElement("when");
valuesWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
valuesChooseEle.addElement(valuesWhenEle);
XmlElement valuesForeachEle = new XmlElement("foreach");
valuesForeachEle.addAttribute(new Attribute("collection", "selective"));
valuesForeachEle.addAttribute(new Attribute("item", "column"));
valuesForeachEle.addAttribute(new Attribute("open", "("));
valuesForeachEle.addAttribute(new Attribute("separator", ","));
valuesForeachEle.addAttribute(new Attribute("close", ")"));
valuesForeachEle.addElement(new TextElement("#{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
valuesWhenEle.addElement(valuesForeachEle);
XmlElement valuesOtherwiseEle = new XmlElement("otherwise");
valuesChooseEle.addElement(valuesOtherwiseEle);
valuesOtherwiseEle.addElement(XmlElementGeneratorTools.generateValuesSelective(columns, "record."));
eleUpsertSelective.addElement(new TextElement("on duplicate key update "));
// update selective
XmlElement setChooseEle = new XmlElement("choose");
eleUpsertSelective.addElement(setChooseEle);
XmlElement setWhenEle = new XmlElement("when");
setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
setChooseEle.addElement(setWhenEle);
XmlElement setForeachEle = new XmlElement("foreach");
setWhenEle.addElement(setForeachEle);
setForeachEle.addAttribute(new Attribute("collection", "selective"));
setForeachEle.addAttribute(new Attribute("item", "column"));
setForeachEle.addAttribute(new Attribute("separator", ","));
// set 操作增加增量插件支持
IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
if (incTools.support()) {
incTools.generateSetsSelectiveWithSelectiveEnhancedPlugin(setForeachEle);
} else {
setForeachEle.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
}
XmlElement setOtherwiseEle = new XmlElement("otherwise"); // 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
// set 操作增加增量插件支持 XmlElementGeneratorTools.useGeneratedKeys(insertEle, introspectedTable);
this.setsSupportIncrementsPlugin(setOtherwiseEle, "record.", true, columns, introspectedTable);
setChooseEle.addElement(setOtherwiseEle);
// insert
insertEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
XmlElement insertColumnsEle = XmlElementGeneratorTools.generateKeysSelective(columns);
insertEle.addElement(insertColumnsEle);
insertEle.addElement(new TextElement("values"));
XmlElement insertValuesEle = XmlElementGeneratorTools.generateValuesSelective(columns);
insertEle.addElement(insertValuesEle);
insertEle.addElement(new TextElement("on duplicate key update "));
// set
XmlElement setsEle = XmlElementGeneratorTools.generateSetsSelective(columns);
insertEle.addElement(setsEle);
document.getRootElement().addElement(eleUpsertSelective); // hook
if (PluginTools.getHook(IUpsertPluginHook.class).sqlMapUpsertSelectiveElementGenerated(insertEle, columns, insertColumnsEle, insertValuesEle, setsEle, introspectedTable)) {
document.getRootElement().addElement(insertEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。"); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
if (this.allowMultiQueries) { }
// ====================================== upsertByExampleSelective ======================================
XmlElement updateEle = new XmlElement("update");
updateEle.addAttribute(new Attribute("id", METHOD_UPSERT_BY_EXAMPLE_SELECTIVE));
// 参数类型
updateEle.addAttribute(new Attribute("parameterType", "map"));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(updateEle);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
// XmlElementGeneratorTools.useGeneratedKeys(updateEle, introspectedTable, "record.");
// update
updateEle.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
updateEle.addElement(new TextElement("set"));
// selective
setChooseEle = new XmlElement("choose");
updateEle.addElement(setChooseEle);
setWhenEle = new XmlElement("when");
setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
setChooseEle.addElement(setWhenEle);
setForeachEle = new XmlElement("foreach");
setWhenEle.addElement(setForeachEle);
setForeachEle.addAttribute(new Attribute("collection", "selective"));
setForeachEle.addAttribute(new Attribute("item", "column"));
setForeachEle.addAttribute(new Attribute("separator", ","));
// set 操作增加增量插件支持
if (incTools.support()) {
incTools.generateSetsSelectiveWithSelectiveEnhancedPlugin(setForeachEle);
} else {
setForeachEle.addElement(new TextElement("${column.value} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
}
setOtherwiseEle = new XmlElement("otherwise");
// set 操作增加增量插件支持
this.setsSupportIncrementsPlugin(setOtherwiseEle, "record.", true, columns, introspectedTable);
setChooseEle.addElement(setOtherwiseEle);
// update where
updateEle.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
// multiQueries
updateEle.addElement(new TextElement(";"));
// insert
updateEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
// selective
insertChooseEle = new XmlElement("choose");
updateEle.addElement(insertChooseEle);
insertWhenEle = new XmlElement("when");
insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
insertChooseEle.addElement(insertWhenEle);
insertForeachEle = new XmlElement("foreach");
insertForeachEle.addAttribute(new Attribute("collection", "selective"));
insertForeachEle.addAttribute(new Attribute("item", "column"));
insertForeachEle.addAttribute(new Attribute("open", "("));
insertForeachEle.addAttribute(new Attribute("separator", ","));
insertForeachEle.addAttribute(new Attribute("close", ")"));
insertForeachEle.addElement(new TextElement("${column.value}"));
insertWhenEle.addElement(insertForeachEle);
insertOtherwiseEle = new XmlElement("otherwise");
insertOtherwiseEle.addElement(XmlElementGeneratorTools.generateKeysSelective(columns, "record."));
insertChooseEle.addElement(insertOtherwiseEle);
insertTrimElement = new XmlElement("trim");
insertTrimElement.addAttribute(new Attribute("prefix", "("));
insertTrimElement.addAttribute(new Attribute("suffix", ")"));
insertTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
insertOtherwiseEle.addElement(insertTrimElement);
this.generateExistsClause(introspectedTable, updateEle, true, columns);
document.getRootElement().addElement(updateEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
}
} else {
// ====================================== upsertSelective ======================================
XmlElement eleUpsertSelective = new XmlElement("insert");
eleUpsertSelective.addAttribute(new Attribute("id", METHOD_UPSERT_SELECTIVE));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(eleUpsertSelective);
if (this.allowMultiQueries) {
// ====================================== upsertByExampleSelective ======================================
XmlElement updateEle = new XmlElement("update");
updateEle.addAttribute(new Attribute("id", METHOD_UPSERT_BY_EXAMPLE_SELECTIVE));
// 参数类型 // 参数类型
eleUpsertSelective.addAttribute(new Attribute("parameterType", introspectedTable.getRules().calculateAllFieldsClass().getFullyQualifiedName())); updateEle.addAttribute(new Attribute("parameterType", "map"));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(updateEle);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer // 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(eleUpsertSelective, introspectedTable); // XmlElementGeneratorTools.useGeneratedKeys(updateEle, introspectedTable, "record.");
// upsertByExample 先执行的update,所以没法获取id
// insert // update
eleUpsertSelective.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime())); updateEle.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateKeysSelective(columns)); updateEle.addElement(new TextElement("set"));
eleUpsertSelective.addElement(new TextElement("values"));
eleUpsertSelective.addElement(XmlElementGeneratorTools.generateValuesSelective(columns));
eleUpsertSelective.addElement(new TextElement("on duplicate key update "));
// set 操作增加增量插件支持 // set 操作增加增量插件支持
this.setsSupportIncrementsPlugin(eleUpsertSelective, null, true, columns, introspectedTable); setsEle = XmlElementGeneratorTools.generateSetsSelective(columns, "record.");
updateEle.addElement(setsEle);
document.getRootElement().addElement(eleUpsertSelective); // update where
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。"); updateEle.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
if (this.allowMultiQueries) {
// ====================================== upsertByExampleSelective ====================================== // multiQueries
XmlElement updateEle = new XmlElement("update"); updateEle.addElement(new TextElement(";"));
updateEle.addAttribute(new Attribute("id", METHOD_UPSERT_BY_EXAMPLE_SELECTIVE));
// 参数类型 // insert
updateEle.addAttribute(new Attribute("parameterType", "map")); updateEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated) insertColumnsEle = XmlElementGeneratorTools.generateKeysSelective(columns, "record.");
commentGenerator.addComment(updateEle); updateEle.addElement(insertColumnsEle);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer insertValuesEle = XmlElementGeneratorTools.generateValuesSelective(columns, "record.", false);
// XmlElementGeneratorTools.useGeneratedKeys(updateEle, introspectedTable, "record."); // 查询值
// upsertByExample 先执行的update,所以没法获取id this.generateExistsClause(introspectedTable, updateEle, Arrays.asList(insertValuesEle));
// update
updateEle.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
updateEle.addElement(new TextElement("set"));
// set 操作增加增量插件支持
this.setsSupportIncrementsPlugin(updateEle, "record.", true, columns, introspectedTable);
// update where
updateEle.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
// multiQueries
updateEle.addElement(new TextElement(";"));
// insert
updateEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
updateEle.addElement(XmlElementGeneratorTools.generateKeysSelective(columns, "record."));
this.generateExistsClause(introspectedTable, updateEle, true, columns);
// hook
if (PluginTools.getHook(IUpsertPluginHook.class).sqlMapUpsertByExampleSelectiveElementGenerated(updateEle, columns, insertColumnsEle, insertValuesEle, setsEle, introspectedTable)) {
document.getRootElement().addElement(updateEle); document.getRootElement().addElement(updateEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。"); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertSelective实现方法。");
} }
...@@ -478,16 +304,18 @@ public class UpsertPlugin extends BasePlugin { ...@@ -478,16 +304,18 @@ public class UpsertPlugin extends BasePlugin {
// insert // insert
insertEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime())); insertEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
for (Element element : this.generateKeys(columns)) { for (Element element : XmlElementGeneratorTools.generateKeys(columns)) {
insertEle.addElement(element); insertEle.addElement(element);
} }
insertEle.addElement(new TextElement("values")); insertEle.addElement(new TextElement("values"));
for (Element element : this.generateValues(columns)) { for (Element element : XmlElementGeneratorTools.generateValues(columns)) {
insertEle.addElement(element); insertEle.addElement(element);
} }
insertEle.addElement(new TextElement("on duplicate key update ")); insertEle.addElement(new TextElement("on duplicate key update "));
// set 操作增加增量插件支持 // set
this.setsSupportIncrementsPlugin(insertEle, null, false, columns, introspectedTable); for (Element set : XmlElementGeneratorTools.generateSets(columns)) {
insertEle.addElement(set);
}
document.getRootElement().addElement(insertEle); document.getRootElement().addElement(insertEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。"); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。");
...@@ -508,8 +336,10 @@ public class UpsertPlugin extends BasePlugin { ...@@ -508,8 +336,10 @@ public class UpsertPlugin extends BasePlugin {
// update // update
updateEle.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); updateEle.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
updateEle.addElement(new TextElement("set")); updateEle.addElement(new TextElement("set"));
// set 操作增加增量插件支持 // set
this.setsSupportIncrementsPlugin(updateEle, "record.", false, columns, introspectedTable); for (Element set : XmlElementGeneratorTools.generateSets(columns, "record.")) {
updateEle.addElement(set);
}
// update where // update where
updateEle.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); updateEle.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
...@@ -519,87 +349,30 @@ public class UpsertPlugin extends BasePlugin { ...@@ -519,87 +349,30 @@ public class UpsertPlugin extends BasePlugin {
// insert // insert
updateEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime())); updateEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
for (Element element : this.generateKeys(columns, "record.")) { for (Element element : XmlElementGeneratorTools.generateKeys(columns)) {
updateEle.addElement(element); updateEle.addElement(element);
} }
this.generateExistsClause(introspectedTable, updateEle, false, columns); this.generateExistsClause(introspectedTable, updateEle, XmlElementGeneratorTools.generateValues(columns, "record.", false));
document.getRootElement().addElement(updateEle); document.getRootElement().addElement(updateEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertByExample实现方法。"); logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertByExample实现方法。");
} }
} }
/**
* sets 节点整合 IncrementsPlugin
* @param element
* @param prefix
* @param selective
* @param columns
* @param introspectedTable
*/
private void setsSupportIncrementsPlugin(XmlElement element, String prefix, boolean selective, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
IncrementsPluginTools incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
if (incTools.support()) {
if (selective) {
element.addElement(incTools.generateSetsSelective(columns, prefix));
} else {
for (Element ele : this.generateCommColumns(columns, prefix, false, 4, introspectedTable)) {
element.addElement(ele);
}
}
} else {
if (selective) {
element.addElement(XmlElementGeneratorTools.generateSetsSelective(columns, prefix));
} else {
for (Element ele : this.generateSets(columns, prefix)) {
element.addElement(ele);
}
}
}
}
/** /**
* exists 语句 * exists 语句
* +635 * +635
* @param introspectedTable * @param introspectedTable
* @param element * @param element
* @param selective * @param values
* @param columns
*/ */
private void generateExistsClause(IntrospectedTable introspectedTable, XmlElement element, boolean selective, List<IntrospectedColumn> columns) { private void generateExistsClause(IntrospectedTable introspectedTable, XmlElement element, List<Element> values) {
element.addElement(new TextElement("select")); element.addElement(new TextElement("select"));
if (selective) {
if (this.withSelectiveEnhancedPlugin) { for (Element value : values) {
// selective element.addElement(value);
XmlElement chooseEle = new XmlElement("choose");
element.addElement(chooseEle);
XmlElement selectWhenEle = new XmlElement("when");
selectWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
chooseEle.addElement(selectWhenEle);
XmlElement valuesForeachEle = new XmlElement("foreach");
valuesForeachEle.addAttribute(new Attribute("collection", "selective"));
valuesForeachEle.addAttribute(new Attribute("item", "column"));
valuesForeachEle.addAttribute(new Attribute("separator", ","));
valuesForeachEle.addElement(new TextElement("#{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
selectWhenEle.addElement(valuesForeachEle);
XmlElement selectOtherwiseEle = new XmlElement("otherwise");
selectOtherwiseEle.addElement(XmlElementGeneratorTools.generateValuesSelective(columns, "record.", false));
chooseEle.addElement(selectOtherwiseEle);
XmlElement valuesTrimElement = new XmlElement("trim");
valuesTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
selectOtherwiseEle.addElement(valuesTrimElement);
} else {
element.addElement(XmlElementGeneratorTools.generateValuesSelective(columns, "record.", false));
}
} else {
for (Element element1 : this.generateValues(columns, "record.", false)) {
element.addElement(element1);
}
} }
element.addElement(new TextElement("from dual where not exists")); element.addElement(new TextElement("from dual where not exists"));
element.addElement(new TextElement("(")); element.addElement(new TextElement("("));
element.addElement(new TextElement("select 1 from " + introspectedTable.getFullyQualifiedTableNameAtRuntime())); element.addElement(new TextElement("select 1 from " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
...@@ -609,207 +382,4 @@ public class UpsertPlugin extends BasePlugin { ...@@ -609,207 +382,4 @@ public class UpsertPlugin extends BasePlugin {
element.addElement(new TextElement(")")); element.addElement(new TextElement(")"));
} }
/**
* 生成values Ele
* @param columns
* @return
*/
private List<Element> generateValues(List<IntrospectedColumn> columns) {
return generateValues(columns, null);
}
/**
* 生成values Ele
* @param columns
* @param prefix
* @return
*/
private List<Element> generateValues(List<IntrospectedColumn> columns, String prefix) {
return generateValues(columns, prefix, true);
}
/**
* 生成values Ele
* @param columns
* @param prefix
* @param bracket
* @return
*/
private List<Element> generateValues(List<IntrospectedColumn> columns, String prefix, boolean bracket) {
return generateCommColumns(columns, prefix, bracket, 2);
}
/**
* 生成keys Ele
* @param columns
* @return
*/
private List<Element> generateKeys(List<IntrospectedColumn> columns) {
return generateKeys(columns, null);
}
/**
* 生成keys Ele
* @param columns
* @param prefix
* @return
*/
private List<Element> generateKeys(List<IntrospectedColumn> columns, String prefix) {
return generateCommColumns(columns, prefix, true, 1);
}
/**
* 生成sets Ele
* @param columns
* @param prefix
* @return
*/
private List<Element> generateSets(List<IntrospectedColumn> columns, String prefix) {
return generateCommColumns(columns, prefix, false, 3);
}
/**
* 通用遍历columns
* @param columns
* @param bracket
* @param prefix
* @param type 1:key,2:value,3:set
* @return
*/
private List<Element> generateCommColumns(List<IntrospectedColumn> columns, String prefix, boolean bracket, int type) {
return this.generateCommColumns(columns, prefix, bracket, type, null);
}
/**
* 通用遍历columns
* @param columns
* @param bracket
* @param prefix
* @param type 1:key,2:value,3:set,4:set(withIncrementsPlugin)
* @param introspectedTable
* @return
*/
private List<Element> generateCommColumns(List<IntrospectedColumn> columns, String prefix, boolean bracket, int type, IntrospectedTable introspectedTable) {
IncrementsPluginTools incTools = null;
if (type == 4) {
incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
}
if (hasIdentityAndGeneratedAlwaysColumns(columns)) {
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", ","));
}
StringBuilder sb = new StringBuilder();
for (IntrospectedColumn introspectedColumn : columns) {
if (introspectedColumn.isGeneratedAlways() || introspectedColumn.isIdentity()) {
if (sb.length() > 0) {
eleTrim.addElement(new TextElement(sb.toString()));
sb.setLength(0);
}
// if 节点
XmlElement eleIf = new XmlElement("if");
eleIf.addAttribute(new Attribute("test", introspectedColumn.getJavaProperty(prefix) + " != null"));
switch (type) {
case 4:
if (incTools.supportColumn(introspectedColumn)) {
for (Element ele : incTools.generatedIncrementsElement(introspectedColumn, prefix, true)) {
eleIf.addElement(ele);
}
} else {
eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = " + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
}
break;
case 3:
eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = " + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
break;
case 2:
eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
break;
case 1:
eleIf.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ","));
break;
}
eleTrim.addElement(eleIf);
} else {
switch (type) {
case 4:
if (incTools.supportColumn(introspectedColumn)) {
if (sb.length() > 0) {
eleTrim.addElement(new TextElement(sb.toString()));
sb.setLength(0);
}
for (Element ele : incTools.generatedIncrementsElement(introspectedColumn, prefix, true)) {
eleTrim.addElement(ele);
}
} else {
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
sb.append(" = ");
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
}
break;
case 3:
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
sb.append(" = ");
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
break;
case 2:
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
break;
case 1:
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
break;
}
sb.append(", ");
}
// 保持和官方一致 80 进行换行
if (type == 1 || type == 2) {
if (sb.length() > 80) {
eleTrim.addElement(new TextElement(sb.toString()));
sb.setLength(0);
OutputUtilities.xmlIndent(sb, 1);
}
} else {
eleTrim.addElement(new TextElement(sb.toString()));
sb.setLength(0);
}
}
if (sb.length() > 0) {
eleTrim.addElement(new TextElement(sb.toString()));
}
return Arrays.asList(eleTrim);
} else if (type == 4) {
return incTools.generateSets(columns, prefix, bracket);
} else {
return XmlElementGeneratorTools.generateCommColumns(columns, prefix, bracket, type);
}
}
/**
* 是否存在自增或者生成的column
* @param columns
* @return
*/
private boolean hasIdentityAndGeneratedAlwaysColumns(List<IntrospectedColumn> columns) {
for (IntrospectedColumn ic : columns) {
if (ic.isGeneratedAlways() || ic.isIdentity()) {
return true;
}
}
return false;
}
} }
\ No newline at end of file
...@@ -18,6 +18,7 @@ package com.itfsw.mybatis.generator.plugins.utils; ...@@ -18,6 +18,7 @@ package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.CommentPlugin; import com.itfsw.mybatis.generator.plugins.CommentPlugin;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.TemplateCommentGenerator; import com.itfsw.mybatis.generator.plugins.utils.enhanced.TemplateCommentGenerator;
import com.itfsw.mybatis.generator.plugins.utils.hook.HookAggregator;
import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.config.Context; import org.mybatis.generator.config.Context;
...@@ -45,19 +46,20 @@ public class BasePlugin extends PluginAdapter { ...@@ -45,19 +46,20 @@ public class BasePlugin extends PluginAdapter {
/** /**
* Set the context under which this plugin is running. * Set the context under which this plugin is running.
* * @param context the new context
* @param context
* the new context
*/ */
@Override @Override
public void setContext(Context context) { public void setContext(Context context) {
super.setContext(context); super.setContext(context);
// 添加插件
HookAggregator.getInstance().setContext(context);
// 配置插件使用的模板引擎 // 配置插件使用的模板引擎
PluginConfiguration cfg = PluginTools.getPluginConfiguration(context, CommentPlugin.class); PluginConfiguration cfg = PluginTools.getPluginConfiguration(context, CommentPlugin.class);
if (cfg == null || cfg.getProperty(CommentPlugin.PRO_TEMPLATE) == null){ if (cfg == null || cfg.getProperty(CommentPlugin.PRO_TEMPLATE) == null) {
if (context.getCommentGenerator() instanceof DefaultCommentGenerator){ if (context.getCommentGenerator() instanceof DefaultCommentGenerator) {
// 使用默认模板引擎 // 使用默认模板引擎
commentGenerator = new TemplateCommentGenerator("default-comment.ftl", true); commentGenerator = new TemplateCommentGenerator("default-comment.ftl", true);
} else { } else {
...@@ -79,7 +81,7 @@ public class BasePlugin extends PluginAdapter { ...@@ -79,7 +81,7 @@ public class BasePlugin extends PluginAdapter {
field.setAccessible(true); field.setAccessible(true);
field.set(context, templateCommentGenerator); field.set(context, templateCommentGenerator);
} catch (Exception e) { } catch (Exception e) {
logger.error("反射异常",e); logger.error("反射异常", e);
} }
} }
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package com.itfsw.mybatis.generator.plugins.utils; package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.utils.hook.HookAggregator;
import org.mybatis.generator.config.Context; import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.PluginConfiguration; import org.mybatis.generator.config.PluginConfiguration;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -36,6 +37,16 @@ import java.util.List; ...@@ -36,6 +37,16 @@ import java.util.List;
public class PluginTools { public class PluginTools {
private static final Logger logger = LoggerFactory.getLogger(PluginTools.class); private static final Logger logger = LoggerFactory.getLogger(PluginTools.class);
/**
* 获取挂载
* @param clazz
* @param <T>
* @return
*/
public static <T> T getHook(Class<T> clazz){
return (T) HookAggregator.getInstance();
}
/** /**
* 检查插件依赖 * 检查插件依赖
* *
......
...@@ -132,6 +132,58 @@ public class XmlElementGeneratorTools { ...@@ -132,6 +132,58 @@ public class XmlElementGeneratorTools {
} }
} }
/**
* 移除 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
* @param element
* @param introspectedTable
*/
public static void removeUseGeneratedKeys(XmlElement element, IntrospectedTable introspectedTable) {
GeneratedKey gk = introspectedTable.getGeneratedKey();
if (gk != null) {
removeAttribute(element, "useGeneratedKeys");
removeAttribute(element, "keyProperty");
removeAttribute(element, "keyColumn");
}
}
/**
* 移除属性
* @param element
* @param name
*/
public static void removeAttribute(XmlElement element, String name){
Iterator<Attribute> iterator = element.getAttributes().iterator();
while (iterator.hasNext()) {
Attribute attribute = iterator.next();
if (attribute.getName().equals(name)) {
iterator.remove();
}
}
}
/**
* 替换属性
* @param element
* @param attribute
*/
public static void replaceAttribute(XmlElement element, Attribute attribute){
removeAttribute(element, attribute.getName());
element.addAttribute(attribute);
}
/**
* xmlElement 替换
* @param srcEle
* @param destEle
*/
public static void replaceXmlElement(XmlElement srcEle, XmlElement destEle){
srcEle.setName(destEle.getName());
srcEle.getAttributes().clear();
srcEle.getAttributes().addAll(destEle.getAttributes());
srcEle.getElements().clear();
srcEle.getElements().addAll(destEle.getElements());
}
/** /**
* 生成keys Ele * 生成keys Ele
* @param columns * @param columns
...@@ -156,7 +208,7 @@ public class XmlElementGeneratorTools { ...@@ -156,7 +208,7 @@ public class XmlElementGeneratorTools {
* @param columns * @param columns
* @return * @return
*/ */
public static Element generateKeysSelective(List<IntrospectedColumn> columns) { public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns) {
return generateKeysSelective(columns, null); return generateKeysSelective(columns, null);
} }
...@@ -166,7 +218,7 @@ public class XmlElementGeneratorTools { ...@@ -166,7 +218,7 @@ public class XmlElementGeneratorTools {
* @param prefix * @param prefix
* @return * @return
*/ */
public static Element generateKeysSelective(List<IntrospectedColumn> columns, String prefix) { public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns, String prefix) {
return generateKeysSelective(columns, prefix, true); return generateKeysSelective(columns, prefix, true);
} }
...@@ -216,7 +268,7 @@ public class XmlElementGeneratorTools { ...@@ -216,7 +268,7 @@ public class XmlElementGeneratorTools {
* @param columns * @param columns
* @return * @return
*/ */
public static Element generateValuesSelective(List<IntrospectedColumn> columns) { public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns) {
return generateValuesSelective(columns, null); return generateValuesSelective(columns, null);
} }
...@@ -226,7 +278,7 @@ public class XmlElementGeneratorTools { ...@@ -226,7 +278,7 @@ public class XmlElementGeneratorTools {
* @param prefix * @param prefix
* @return * @return
*/ */
public static Element generateValuesSelective(List<IntrospectedColumn> columns, String prefix) { public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns, String prefix) {
return generateValuesSelective(columns, prefix, true); return generateValuesSelective(columns, prefix, true);
} }
......
/*
* 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.
*/
package com.itfsw.mybatis.generator.plugins.utils.hook;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/4/27 11:33
* ---------------------------------------------------------------------------
*/
public class HookAggregator implements IUpsertPluginHook {
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class); // 日志
private final static HookAggregator instance = new HookAggregator();
private Context context;
/**
* constructor
*/
public HookAggregator() {
}
/**
* Getter method for property <tt>instance</tt>.
* @return property value of instance
* @author hewei
*/
public static HookAggregator getInstance() {
return instance;
}
/**
* Setter method for property <tt>context</tt>.
* @param context value to be assigned to property context
* @author hewei
*/
public void setContext(Context context) {
this.context = context;
}
/**
* 获取挂载
* @param clazz
* @param <T>
* @return
*/
public <T> T getHook(Class<T> clazz) {
return (T) this;
}
/**
* 获取插件
* @param clazz
* @param <T>
* @return
*/
private <T> List<T> getPlugins(Class<T> clazz) {
List list = new ArrayList();
// 反射获取插件列表,不能用单例去弄,不然因为类释放的问题而导致测试用例出问题
try {
java.lang.reflect.Field field = this.context.getPlugins().getClass().getDeclaredField("plugins");
field.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) field.get(this.context.getPlugins());
for (Plugin plugin : plugins) {
if (clazz.isInstance(plugin)) {
list.add(plugin);
}
}
} catch (Exception e) {
logger.error("获取插件列表失败!", e);
}
return list;
}
// ================================================= default ===============================================
@Override
public boolean clientUpsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.clientUpsertSelectiveMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean clientUpsertByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.clientUpsertByExampleSelectiveMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.sqlMapUpsertSelectiveElementGenerated(element, columns, insertColumnsEle, insertValuesEle, setsEle, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.sqlMapUpsertByExampleSelectiveElementGenerated(element, columns, insertColumnsEle, insertValuesEle, setsEle, introspectedTable)) {
return false;
}
}
return true;
}
}
/*
* 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.
*/
package com.itfsw.mybatis.generator.plugins.utils.hook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/4/27 11:09
* ---------------------------------------------------------------------------
*/
public interface IUpsertPluginHook {
/**
* upsertSelective 方法
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
boolean clientUpsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable);
/**
* upsertByExampleSelective 方法
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
boolean clientUpsertByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable);
/**
* upsertSelective xml
* @param element
* @param columns
* @param insertColumnsEle
* @param insertValuesEle
* @param setsEle
* @param introspectedTable
* @return
*/
boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable);
/**
* upsertByExampleSelective xml
* @param element
* @param columns
* @param insertColumnsEle
* @param insertValuesEle
* @param setsEle
* @param introspectedTable
* @return
*/
boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable);
}
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.*;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.sql.SQLException;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/7/28 15:47
* ---------------------------------------------------------------------------
*/
public class OldSelectiveEnhancedPluginTest {
/**
* 初始化数据库
*/
@BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException {
DBHelper.createDB("scripts/OldSelectiveEnhancedPlugin/init.sql");
}
/**
* 测试配置异常
*/
@Test
public void testWarnings() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
// 1. 没有配置ModelColumnPlugin插件
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator-without-ModelColumnPlugin.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
// 2. 没有配置UpsertPlugin插件位置配置错误
tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator-with-UpsertPlugin-with-wrong-place.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin插件建议配置在插件com.itfsw.mybatis.generator.plugins.UpsertPlugin后面,否则某些功能可能得不到增强!");
}
/**
* 测试Model
*/
@Test
public void testModel() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
Assert.assertTrue((Boolean) tb.invoke("hasSelective"));
Assert.assertTrue((Boolean) tb.invoke("hasSelective", "field_1"));
Assert.assertFalse((Boolean) tb.invoke("hasSelective", "inc_f1"));
Assert.assertTrue((Boolean) tb.invoke("hasSelective", "inc_f2"));
}
});
}
/**
* 测试insertSelective增强
*/
@Test
public void testInsertSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 111L);
tb.set("incF3", 10l);
tb.set("tsIncF2", 5l);
// selective
ObjectUtil TbColumnId = new ObjectUtil(loader, packagz + ".Tb$Column#id");
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 3);
Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnField1.getObject());
Array.set(columns, 2, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject());
Assert.assertEquals(sql, "insert into tb ( id, field_1, inc_f2 ) values ( 111, 'null', 5 )");
Object result = tbMapper.invoke("insertSelective", tb.getObject());
Assert.assertEquals(result, 1);
}
});
}
/**
* 测试 updateByExampleSelective
*/
@Test
public void testUpdateByExampleSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
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", 1l);
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("incF3", 10l);
tb.set("tsIncF2", 5l);
// selective
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(sql, "update tb SET field_1 = 'null', inc_f2 = 5 WHERE ( id = '1' )");
Object result = tbMapper.invoke("updateByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(result, 1);
}
});
}
/**
* 测试 updateByPrimaryKeySelective
*/
@Test
public void testUpdateByPrimaryKeySelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 2l);
tb.set("incF3", 10l);
tb.set("tsIncF2", 5l);
// selective
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByPrimaryKeySelective", tb.getObject());
Assert.assertEquals(sql, "update tb SET field_1 = 'null', inc_f2 = 5 where id = 2");
Object result = tbMapper.invoke("updateByPrimaryKeySelective", tb.getObject());
Assert.assertEquals(result, 1);
}
});
}
/**
* 测试 upsertSelective
*/
@Test
public void testUpsertSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 10l);
tb.set("incF3", 10l);
tb.set("tsIncF2", 5l);
// selective
ObjectUtil TbColumnId = new ObjectUtil(loader, packagz + ".Tb$Column#id");
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 3);
Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnField1.getObject());
Array.set(columns, 2, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// 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");
Object result = tbMapper.invoke("upsertSelective", tb.getObject());
Assert.assertEquals(result, 1);
}
});
}
/**
* 测试 upsertByExampleSelective
*/
@Test
public void testUpsertByExampleSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OldSelectiveEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
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", 99l);
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 99l);
tb.set("incF3", 10l);
tb.set("tsIncF2", 5l);
// selective
ObjectUtil TbColumnId = new ObjectUtil(loader, packagz + ".Tb$Column#id");
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 3);
Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnField1.getObject());
Array.set(columns, 2, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(sql, "update tb set id = 99, inc_f2 = 5, inc_f3 = 10 WHERE ( id = '99' ) ; insert into tb ( id, field_1, inc_f2 ) select 99, 'null', 5 from dual where not exists ( select 1 from tb WHERE ( id = '99' ) )");
Object result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(result, 0);
result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(result, 1);
}
});
}
}
...@@ -42,7 +42,7 @@ public class SelectiveEnhancedPluginTest { ...@@ -42,7 +42,7 @@ public class SelectiveEnhancedPluginTest {
*/ */
@BeforeClass @BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException { public static void init() throws SQLException, IOException, ClassNotFoundException {
DBHelper.createDB("scripts/OldSelectiveEnhancedPlugin/init.sql"); DBHelper.createDB("scripts/SelectiveEnhancedPlugin/init.sql");
} }
/** /**
...@@ -54,11 +54,6 @@ public class SelectiveEnhancedPluginTest { ...@@ -54,11 +54,6 @@ public class SelectiveEnhancedPluginTest {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-without-ModelColumnPlugin.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-without-ModelColumnPlugin.xml");
tool.generate(); tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!"); Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
// 2. 同时配置了OldSelectiveEnhancedPlugin插件
tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-with-OldSelectiveEnhancedPlugin.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin不能和com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin插件同时使用!");
} }
/** /**
......
...@@ -19,7 +19,6 @@ package com.itfsw.mybatis.generator.plugins; ...@@ -19,7 +19,6 @@ package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.*; import com.itfsw.mybatis.generator.plugins.tools.*;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.exception.XMLParserException;
...@@ -37,13 +36,6 @@ import java.sql.SQLException; ...@@ -37,13 +36,6 @@ import java.sql.SQLException;
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
*/ */
public class UpsertPluginTest { public class UpsertPluginTest {
/**
* 初始化数据库
*/
@BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException {
DBHelper.createDB("scripts/UpsertPlugin/init.sql");
}
/** /**
* 测试配置异常 * 测试配置异常
...@@ -67,7 +59,7 @@ public class UpsertPluginTest { ...@@ -67,7 +59,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsert() throws Exception { public void testUpsert() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
...@@ -99,7 +91,7 @@ public class UpsertPluginTest { ...@@ -99,7 +91,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertWithBLOBs() throws Exception { public void testUpsertWithBLOBs() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 多个 blob // 1. 多个 blob
...@@ -153,7 +145,7 @@ public class UpsertPluginTest { ...@@ -153,7 +145,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertSelective() throws Exception { public void testUpsertSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 普通 // 1. 普通
...@@ -192,7 +184,7 @@ public class UpsertPluginTest { ...@@ -192,7 +184,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertByExample() throws Exception { public void testUpsertByExample() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
...@@ -228,7 +220,7 @@ public class UpsertPluginTest { ...@@ -228,7 +220,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertByExampleWithBLOBs() throws Exception { public void testUpsertByExampleWithBLOBs() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 多个 blob // 1. 多个 blob
...@@ -289,7 +281,7 @@ public class UpsertPluginTest { ...@@ -289,7 +281,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertByExampleSelective() throws Exception { public void testUpsertByExampleSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 普通 // 1. 普通
...@@ -334,7 +326,7 @@ public class UpsertPluginTest { ...@@ -334,7 +326,7 @@ public class UpsertPluginTest {
@Test @Test
public void testWithIdentityAndGeneratedAlwaysColumns() throws Exception { public void testWithIdentityAndGeneratedAlwaysColumns() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// ------------------------------------------ upsert --------------------------------------------------- // ------------------------------------------ upsert ---------------------------------------------------
......
...@@ -64,33 +64,29 @@ public class DBHelper { ...@@ -64,33 +64,29 @@ public class DBHelper {
String password = properties.getProperty("password"); String password = properties.getProperty("password");
// 获取connection // 获取connection
Class.forName(driver); Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password); try (
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
// 获取建表和初始化sql // 获取建表和初始化sql
InputStream inputStream = Resources.getResourceAsStream(resource); InputStream inputStream = Resources.getResourceAsStream(resource);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取sql语句执行 ) {
StringBuffer sb = new StringBuffer(); // 读取sql语句执行
String line; StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) { String line;
sb.append(line).append("\n"); while ((line = bufferedReader.readLine()) != null) {
if (line.matches(".*;$")) { sb.append(line).append("\n");
statement.execute(sb.toString()); if (line.matches(".*;$")) {
sb.setLength(0); statement.execute(sb.toString());
sb.setLength(0);
}
} }
} }
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
statement.close();
connection.close();
} }
/** /**
* 执行sql * 执行sql
*
* @param sqlSession * @param sqlSession
* @param sql * @param sql
* @return * @return
...@@ -102,7 +98,6 @@ public class DBHelper { ...@@ -102,7 +98,6 @@ public class DBHelper {
/** /**
* 执行sql * 执行sql
*
* @param connection * @param connection
* @param sql * @param sql
* @return * @return
......
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50617
Source Host : localhost:3306
Source Database : mybatis-generator-plugin
Target Server Type : MYSQL
Target Server Version : 50617
File Encoding : 65001
Date: 2017-07-05 17:21:41
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL COMMENT '注释1',
`field_1` varchar(255) DEFAULT NULL COMMENT '注释2',
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
-- ----------------------------
INSERT INTO `tb` VALUES ('1', 'fd1', '0', '0', '0');
INSERT INTO `tb` VALUES ('2', 'fd2', '1', '2', '3');
INSERT INTO `tb` VALUES ('3', null, '3', '2', '1');
INSERT INTO `tb` VALUES ('4', 'fd3', '1', '1', '1');
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2017.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2017.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin" />
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2017.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin">
<property name="allowMultiQueries" value="true"/>
</plugin>
<plugin type="com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin"/>
<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=""/>
<!--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">
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?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.SelectiveEnhancedPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin" />
<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=""/>
<!--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">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</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