Commit a8c0a38a authored by hewei's avatar hewei

重写 SelectiveEnhanced 插件

parent 75509542
...@@ -99,7 +99,12 @@ public class IncrementsPlugin extends BasePlugin { ...@@ -99,7 +99,12 @@ public class IncrementsPlugin extends BasePlugin {
*/ */
@Override @Override
public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
if (PluginTools.checkDependencyPlugin(context, SelectiveEnhancedPlugin.class)) {
// TODO SelectiveEnhancedPlugin.sqlMapUpdateByExampleSelectiveElementGenerated
} else {
generatedWithSelective(element, introspectedTable, true); generatedWithSelective(element, introspectedTable, true);
}
return true; return true;
} }
...@@ -135,7 +140,12 @@ public class IncrementsPlugin extends BasePlugin { ...@@ -135,7 +140,12 @@ public class IncrementsPlugin extends BasePlugin {
*/ */
@Override @Override
public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
if (PluginTools.checkDependencyPlugin(context, SelectiveEnhancedPlugin.class)) {
// TODO SelectiveEnhancedPlugin.sqlMapUpdateByPrimaryKeySelectiveElementGenerated
} else {
generatedWithSelective(element, introspectedTable, false); generatedWithSelective(element, introspectedTable, false);
}
return true; return true;
} }
......
...@@ -339,21 +339,7 @@ public class LogicalDeletePlugin extends BasePlugin { ...@@ -339,21 +339,7 @@ public class LogicalDeletePlugin extends BasePlugin {
logicalDeleteByPrimaryKey.addElement(new TextElement(sb1.toString())); logicalDeleteByPrimaryKey.addElement(new TextElement(sb1.toString()));
boolean and = false; XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(logicalDeleteByPrimaryKey, introspectedTable.getPrimaryKeyColumns());
for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
sb.setLength(0);
if (and) {
sb.append(" and ");
} else {
sb.append("where ");
and = true;
}
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
sb.append(" = ");
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn));
logicalDeleteByPrimaryKey.addElement(new TextElement(sb.toString()));
}
document.getRootElement().addElement(logicalDeleteByPrimaryKey); document.getRootElement().addElement(logicalDeleteByPrimaryKey);
logger.debug("itfsw(逻辑删除插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加方法logicalDeleteByPrimaryKey的实现。"); logger.debug("itfsw(逻辑删除插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加方法logicalDeleteByPrimaryKey的实现。");
...@@ -394,21 +380,7 @@ public class LogicalDeletePlugin extends BasePlugin { ...@@ -394,21 +380,7 @@ public class LogicalDeletePlugin extends BasePlugin {
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()); sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectByPrimaryKey.addElement(new TextElement(sb.toString())); selectByPrimaryKey.addElement(new TextElement(sb.toString()));
and = false; XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(selectByPrimaryKey, introspectedTable.getPrimaryKeyColumns());
for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
sb.setLength(0);
if (and) {
sb.append(" and ");
} else {
sb.append("where ");
and = true;
}
sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
sb.append(" = ");
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn));
selectByPrimaryKey.addElement(new TextElement(sb.toString()));
}
// 逻辑删除的判断 // 逻辑删除的判断
sb.setLength(0); sb.setLength(0);
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
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.JavaElementGeneratorTools;
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.*; import org.mybatis.generator.api.dom.java.*;
...@@ -73,12 +74,11 @@ public class ModelColumnPlugin extends BasePlugin { ...@@ -73,12 +74,11 @@ public class ModelColumnPlugin extends BasePlugin {
/** /**
* 生成Column字段枚举 * 生成Column字段枚举
*
* @param topLevelClass * @param topLevelClass
* @param introspectedTable * @param introspectedTable
* @return * @return
*/ */
private InnerEnum generateColumnEnum(TopLevelClass topLevelClass, IntrospectedTable introspectedTable){ private InnerEnum generateColumnEnum(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 生成内部枚举 // 生成内部枚举
InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(ENUM_NAME)); InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(ENUM_NAME));
innerEnum.setVisibility(JavaVisibility.PUBLIC); innerEnum.setVisibility(JavaVisibility.PUBLIC);
...@@ -93,6 +93,18 @@ public class ModelColumnPlugin extends BasePlugin { ...@@ -93,6 +93,18 @@ public class ModelColumnPlugin extends BasePlugin {
commentGenerator.addFieldComment(columnField, introspectedTable); commentGenerator.addFieldComment(columnField, introspectedTable);
innerEnum.addField(columnField); innerEnum.addField(columnField);
Field javaPropertyField = new Field("javaProperty", FullyQualifiedJavaType.getStringInstance());
javaPropertyField.setVisibility(JavaVisibility.PRIVATE);
javaPropertyField.setFinal(true);
commentGenerator.addFieldComment(javaPropertyField, introspectedTable);
innerEnum.addField(javaPropertyField);
Field jdbcTypeField = new Field("jdbcType", FullyQualifiedJavaType.getStringInstance());
jdbcTypeField.setVisibility(JavaVisibility.PRIVATE);
jdbcTypeField.setFinal(true);
commentGenerator.addFieldComment(jdbcTypeField, introspectedTable);
innerEnum.addField(jdbcTypeField);
Method mValue = new Method("value"); Method mValue = new Method("value");
mValue.setVisibility(JavaVisibility.PUBLIC); mValue.setVisibility(JavaVisibility.PUBLIC);
mValue.setReturnType(FullyQualifiedJavaType.getStringInstance()); mValue.setReturnType(FullyQualifiedJavaType.getStringInstance());
...@@ -107,10 +119,22 @@ public class ModelColumnPlugin extends BasePlugin { ...@@ -107,10 +119,22 @@ public class ModelColumnPlugin extends BasePlugin {
commentGenerator.addGeneralMethodComment(mGetValue, introspectedTable); commentGenerator.addGeneralMethodComment(mGetValue, introspectedTable);
innerEnum.addMethod(mGetValue); innerEnum.addMethod(mGetValue);
Method mGetJavaProperty = JavaElementGeneratorTools.generateGetterMethod(javaPropertyField);
commentGenerator.addGeneralMethodComment(mGetJavaProperty, introspectedTable);
innerEnum.addMethod(mGetJavaProperty);
Method mGetJdbcType = JavaElementGeneratorTools.generateGetterMethod(jdbcTypeField);
commentGenerator.addGeneralMethodComment(mGetJdbcType, introspectedTable);
innerEnum.addMethod(mGetJdbcType);
Method constructor = new Method(ENUM_NAME); Method constructor = new Method(ENUM_NAME);
constructor.setConstructor(true); constructor.setConstructor(true);
constructor.addBodyLine("this.column = column;"); constructor.addBodyLine("this.column = column;");
constructor.addBodyLine("this.javaProperty = javaProperty;");
constructor.addBodyLine("this.jdbcType = jdbcType;");
constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "column"));
constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "javaProperty"));
constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "jdbcType"));
commentGenerator.addGeneralMethodComment(constructor, introspectedTable); commentGenerator.addGeneralMethodComment(constructor, introspectedTable);
innerEnum.addMethod(constructor); innerEnum.addMethod(constructor);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。"); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。");
...@@ -123,6 +147,10 @@ public class ModelColumnPlugin extends BasePlugin { ...@@ -123,6 +147,10 @@ public class ModelColumnPlugin extends BasePlugin {
sb.append(field.getName()); sb.append(field.getName());
sb.append("(\""); sb.append("(\"");
sb.append(introspectedColumn.getActualColumnName()); sb.append(introspectedColumn.getActualColumnName());
sb.append("\", \"");
sb.append(introspectedColumn.getJavaProperty());
sb.append("\", \"");
sb.append(introspectedColumn.getJdbcTypeName());
sb.append("\")"); sb.append("\")");
innerEnum.addEnumConstant(sb.toString()); innerEnum.addEnumConstant(sb.toString());
......
...@@ -346,7 +346,7 @@ public class XmlElementGeneratorTools { ...@@ -346,7 +346,7 @@ public class XmlElementGeneratorTools {
sb.setLength(0); sb.setLength(0);
} }
} }
if (sb.length() > 0 || bracket){ if (sb.length() > 0 || bracket) {
list.add(new TextElement(sb.append(bracket ? ")" : "").toString())); list.add(new TextElement(sb.append(bracket ? ")" : "").toString()));
} }
...@@ -372,6 +372,21 @@ public class XmlElementGeneratorTools { ...@@ -372,6 +372,21 @@ public class XmlElementGeneratorTools {
} }
for (IntrospectedColumn introspectedColumn : columns) { for (IntrospectedColumn introspectedColumn : columns) {
if (type != 3 && (introspectedColumn.isSequenceColumn() || introspectedColumn.getFullyQualifiedJavaType().isPrimitive())) {
// if it is a sequence column, it is not optional
// This is required for MyBatis3 because MyBatis3 parses
// and calculates the SQL before executing the selectKey
// if it is primitive, we cannot do a null check
switch (type) {
case 2:
eleTrim.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
break;
case 1:
eleTrim.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ","));
break;
}
} else {
XmlElement eleIf = new XmlElement("if"); XmlElement eleIf = new XmlElement("if");
eleIf.addAttribute(new Attribute("test", introspectedColumn.getJavaProperty(prefix) + " != null")); eleIf.addAttribute(new Attribute("test", introspectedColumn.getJavaProperty(prefix) + " != null"));
...@@ -389,6 +404,7 @@ public class XmlElementGeneratorTools { ...@@ -389,6 +404,7 @@ public class XmlElementGeneratorTools {
eleTrim.addElement(eleIf); eleTrim.addElement(eleIf);
} }
}
return eleTrim; return eleTrim;
} }
...@@ -413,4 +429,39 @@ public class XmlElementGeneratorTools { ...@@ -413,4 +429,39 @@ public class XmlElementGeneratorTools {
return list; return list;
} }
/**
* 生成 xxxByPrimaryKey 的where 语句
* @param element
* @param primaryKeyColumns
* @return
*/
public static void generateWhereByPrimaryKeyTo(XmlElement element, List<IntrospectedColumn> primaryKeyColumns) {
generateWhereByPrimaryKeyTo(element, primaryKeyColumns, null);
}
/**
* 生成 xxxByPrimaryKey 的where 语句
* @param element
* @param primaryKeyColumns
* @param prefix
* @return
*/
public static void generateWhereByPrimaryKeyTo(XmlElement element, List<IntrospectedColumn> primaryKeyColumns, String prefix) {
StringBuilder sb = new StringBuilder();
boolean and = false;
for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {
sb.setLength(0);
if (and) {
sb.append(" and ");
} else {
sb.append("where ");
and = true;
}
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
sb.append(" = ");
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix));
element.addElement(new TextElement(sb.toString()));
}
}
} }
/* /*
* Copyright (c) 2017. * Copyright (c) 2018.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -33,7 +33,7 @@ import java.sql.SQLException; ...@@ -33,7 +33,7 @@ import java.sql.SQLException;
* *
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
* @author: hewei * @author: hewei
* @time:2017/7/28 15:47 * @time:2018/4/20 10:57
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
*/ */
public class SelectiveEnhancedPluginTest { public class SelectiveEnhancedPluginTest {
...@@ -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/SelectiveEnhancedPlugin/init.sql"); DBHelper.createDB("scripts/OldSelectiveEnhancedPlugin/init.sql");
} }
/** /**
...@@ -55,36 +55,10 @@ public class SelectiveEnhancedPluginTest { ...@@ -55,36 +55,10 @@ public class SelectiveEnhancedPluginTest {
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. 没有配置UpsertPlugin插件位置配置错误 // 2. 同时配置了OldSelectiveEnhancedPlugin插件
tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-with-UpsertPlugin-with-wrong-place.xml"); tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-with-OldSelectiveEnhancedPlugin.xml");
tool.generate(); tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin插件建议配置在插件com.itfsw.mybatis.generator.plugins.UpsertPlugin后面,否则某些功能可能得不到增强!"); Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin不能和com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin插件同时使用!");
}
/**
* 测试Model
*/
@Test
public void testModel() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/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"));
}
});
} }
/** /**
...@@ -107,12 +81,11 @@ public class SelectiveEnhancedPluginTest { ...@@ -107,12 +81,11 @@ public class SelectiveEnhancedPluginTest {
Object columns = Array.newInstance(TbColumnField1.getCls(), 2); Object columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject()); Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject()); Array.set(columns, 1, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql // sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject()); String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( field_1, inc_f2 ) values ( 'null', 5 )"); Assert.assertEquals(sql, "insert into tb ( field_1 , inc_f2 ) values ( 'null' , 5 )");
Object result = tbMapper.invoke("insertSelective", tb.getObject()); Object result = tbMapper.invoke("insertSelective", tb.getObject(), columns);
Assert.assertEquals(result, 1); Assert.assertEquals(result, 1);
} }
}); });
...@@ -142,12 +115,11 @@ public class SelectiveEnhancedPluginTest { ...@@ -142,12 +115,11 @@ public class SelectiveEnhancedPluginTest {
Object columns = Array.newInstance(TbColumnField1.getCls(), 2); Object columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject()); Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject()); Array.set(columns, 1, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql // sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tb.getObject(), TbExample.getObject()); String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tb.getObject(), TbExample.getObject(), columns);
Assert.assertEquals(sql, "update tb SET field_1 = 'null', inc_f2 = 5 WHERE ( id = '1' )"); Assert.assertEquals(sql, "update tb SET field_1 = 'null' , inc_f2 = 5 WHERE ( id = '1' )");
Object result = tbMapper.invoke("updateByExampleSelective", tb.getObject(), TbExample.getObject()); Object result = tbMapper.invoke("updateByExampleSelective", tb.getObject(), TbExample.getObject(), columns);
Assert.assertEquals(result, 1); Assert.assertEquals(result, 1);
} }
}); });
...@@ -174,12 +146,11 @@ public class SelectiveEnhancedPluginTest { ...@@ -174,12 +146,11 @@ public class SelectiveEnhancedPluginTest {
Object columns = Array.newInstance(TbColumnField1.getCls(), 2); Object columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject()); Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject()); Array.set(columns, 1, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql // sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByPrimaryKeySelective", tb.getObject()); String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByPrimaryKeySelective", tb.getObject(), columns);
Assert.assertEquals(sql, "update tb SET field_1 = 'null', inc_f2 = 5 where id = 2"); Assert.assertEquals(sql, "update tb SET field_1 = 'null' , inc_f2 = 5 where id = 2");
Object result = tbMapper.invoke("updateByPrimaryKeySelective", tb.getObject()); Object result = tbMapper.invoke("updateByPrimaryKeySelective", tb.getObject(), columns);
Assert.assertEquals(result, 1); Assert.assertEquals(result, 1);
} }
}); });
...@@ -208,12 +179,11 @@ public class SelectiveEnhancedPluginTest { ...@@ -208,12 +179,11 @@ public class SelectiveEnhancedPluginTest {
Array.set(columns, 0, TbColumnId.getObject()); Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnField1.getObject()); Array.set(columns, 1, TbColumnField1.getObject());
Array.set(columns, 2, TbColumnTsIncF2.getObject()); Array.set(columns, 2, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql // sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertSelective", tb.getObject()); String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertSelective", tb.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( id, field_1, inc_f2 ) values ( 10, 'null', 5 ) on duplicate key update id = 10, field_1 = 'null', inc_f2 = 5"); Assert.assertEquals(sql, "insert into tb ( id , field_1 , inc_f2 ) values ( 10 , 'null' , 5 ) on duplicate key update id = 10 , field_1 = 'null' , inc_f2 = 5");
Object result = tbMapper.invoke("upsertSelective", tb.getObject()); Object result = tbMapper.invoke("upsertSelective", tb.getObject(), columns);
Assert.assertEquals(result, 1); Assert.assertEquals(result, 1);
} }
}); });
...@@ -246,14 +216,13 @@ public class SelectiveEnhancedPluginTest { ...@@ -246,14 +216,13 @@ public class SelectiveEnhancedPluginTest {
Array.set(columns, 0, TbColumnId.getObject()); Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnField1.getObject()); Array.set(columns, 1, TbColumnField1.getObject());
Array.set(columns, 2, TbColumnTsIncF2.getObject()); Array.set(columns, 2, TbColumnTsIncF2.getObject());
tb.invoke("selective", columns);
// sql // sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertByExampleSelective", tb.getObject(), TbExample.getObject()); String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "upsertByExampleSelective", tb.getObject(), TbExample.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( id, field_1, inc_f2 ) select 99, 'null', 5 from dual where not exists ( select 1 from tb WHERE ( id = '99' ) ) ; update tb set inc_f2 = 5, inc_f3 = 10 WHERE ( id = '99' )"); Assert.assertEquals(sql, "insert into tb ( id , field_1 , inc_f2 ) select 99 , 'null' , 5 from dual where not exists ( select 1 from tb WHERE ( id = '99' ) ) ; update tb set id = 99 , field_1 = 'null' , inc_f2 = 5 WHERE ( id = '99' )");
Object result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject()); Object result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject(), columns);
Assert.assertEquals(result, 1); Assert.assertEquals(result, 1);
result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject()); result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject(), columns);
Assert.assertEquals(result, 0); Assert.assertEquals(result, 0);
} }
}); });
......
...@@ -60,7 +60,7 @@ public class SqlHelper { ...@@ -60,7 +60,7 @@ public class SqlHelper {
*/ */
public static String getFormatMapperSql(Object mapper, String methodName, Object... args) { public static String getFormatMapperSql(Object mapper, String methodName, Object... args) {
String sql = getMapperSql(mapper, methodName, args); String sql = getMapperSql(mapper, methodName, args);
return sql == null ? null : sql.replaceAll("\n\\s*", " "); return sql == null ? null : sql.replaceAll("\n", " ").replaceAll("\\s+", " ");
} }
/** /**
......
<?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
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
~ Copyright (c) 2017. ~ Copyright (c) 2018.
~ ~
~ Licensed under the Apache License, Version 2.0 (the "License"); ~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License. ~ you may not use this file except in compliance with the License.
......
<?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.UpsertPlugin">
<property name="allowMultiQueries" value="true"/>
</plugin>
<plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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