Commit 75509542 authored by hewei's avatar hewei

SelectiveEnhancedPlugin -> OldSelectiveEnhancedPlugin 并过期

parent 6b3ecaee
/*
* 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(0), "record.", introspectedTable);
// upsertByExampleSelective的第二个trim比较特殊,需另行处理
this.replaceEleForUpsertByExampleSelective(eles.get(1), "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) 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 IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
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 IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
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("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(), "insertSelective", tb.getObject());
Assert.assertEquals(sql, "insert into tb ( field_1, inc_f2 ) values ( 'null', 5 )");
Object result = tbMapper.invoke("insertSelective", tb.getObject());
Assert.assertEquals(result, 1);
}
});
}
/**
* 测试 updateByExampleSelective
*/
@Test
public void testUpdateByExampleSelective() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
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 IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
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 IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
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 IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException {
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, "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' )");
Object result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(result, 1);
result = tbMapper.invoke("upsertByExampleSelective", tb.getObject(), TbExample.getObject());
Assert.assertEquals(result, 0);
}
});
}
}
/*
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 AUTO_INCREMENT 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
......@@ -24,7 +24,7 @@
<!--导入属性配置 -->
<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"/>
<plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin"/>
......
<?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
......@@ -27,7 +27,7 @@
<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.OldSelectiveEnhancedPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
......
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