Compare commits

..
20 Commits
Author SHA1 Message Date
hewei f0a92c5d6b [maven-release-plugin] prepare release V1.2.5 2018-05-18 11:23:20 +08:00
hewei 15cc5eade9 V1.2.5 2018-05-18 11:21:36 +08:00
hewei 887bd057fd 过时文档删除 2018-05-18 11:10:08 +08:00
hewei 1ebf829d57 切换数据库引擎,加快测试用例执行速度 2018-05-17 18:01:34 +08:00
hewei a87dcf9a01 UpsertPlugin 插件增加批量操作方法 2018-05-17 17:49:09 +08:00
hewei f6b040a4ff BatchInsertPlugin 增加 allowMultiQueries配置,开启时在不传指定列时启用原生非空判断 2018-05-17 13:28:15 +08:00
hewei c8869e95c1 V1.2.4 2018-05-16 18:36:30 +08:00
hewei 787a0da847 [maven-release-plugin] prepare for next development iteration 2018-05-16 18:28:54 +08:00
hewei 9e973ceeaa [maven-release-plugin] prepare release V1.2.4 2018-05-16 18:28:25 +08:00
hewei e4164726ce ModelColumnPlugin增加excludes方法 2018-05-16 18:24:25 +08:00
hewei ba73f0ac6a ModelColumnPlugin增加excludes方法 2018-05-16 18:13:27 +08:00
hewei 5328015116 去掉过期方法 2018-05-16 15:43:29 +08:00
hewei 50e1cd73f1 V1.2.3 2018-05-16 14:22:23 +08:00
hewei 9758855579 [maven-release-plugin] prepare for next development iteration 2018-05-16 14:16:59 +08:00
hewei 72f83b0ca0 [maven-release-plugin] prepare release V1.2.3 2018-05-16 14:16:40 +08:00
hewei 4108a42b17 [issues#26][issues#27]:插件因为是复用的,需要进行属性的清空。 2018-05-16 14:13:42 +08:00
hewei d523989209 [issues#26][issues#27]:插件因为是复用的,需要进行属性的清空。 2018-05-16 14:03:07 +08:00
hewei 50b139f290 [issues#26][issues#27]:插件因为是复用的,需要进行属性的清空。 2018-05-16 13:54:55 +08:00
hewei 567279dbca V1.2.2 2018-05-14 15:24:46 +08:00
hewei 4c5695c75d [maven-release-plugin] prepare for next development iteration 2018-05-14 14:35:51 +08:00
26 changed files with 869 additions and 116 deletions
+34 -8
View File
@@ -30,7 +30,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.1</version>
<version>1.2.5</version>
</dependency>
```
---------------------------------------
@@ -311,14 +311,17 @@ Mybatis Generator 插件默认把Model类和Example类都生成到一个包下
</plugin>
```
### 6. 批量插入插件
提供了批量插入batchInsert和batchInsertSelective方法,因为方法使用了使用了JDBC的getGenereatedKeys方法返回插入主键,所以只能在MYSQL和SQLServer下使用。
需配合数据Model属性对应Column获取插件(ModelColumnPlugin)插件使用,实现类似于insertSelective插入列!
PS:为了和Mybatis官方代码风格保持一致,1.0.5+版本把批量插入方法分开了,基于老版本1.0.5-版本生成的代码请继续使用“com.itfsw.mybatis.generator.plugins.BatchInsertOldPlugin”不影响使用
PS:继续PS,本来想继续保留老版本代码,不影响老版本已经生成代码使用的,但是始终没有绕过BindingException,只能把代码移入BatchInsertOldPlugin类~~~~~
提供了批量插入batchInsert和batchInsertSelective方法,需配合数据Model属性对应Column获取插件(ModelColumnPlugin)插件使用,实现类似于insertSelective插入列!
插件:
```xml
<!-- 批量插入插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin">
<!--
开启后可以实现官方插件根据属性是否为空决定是否插入该字段功能
!需开启allowMultiQueries=true多条sql提交操作,所以不建议使用!插件默认不开启
-->
<property name="allowMultiQueries" value="false"/>
</plugin>
```
使用:
```java
@@ -346,6 +349,8 @@ public class Test {
this.tbMapper.batchInsert(list);
// !!!下面按需插入指定列(类似于insertSelective),需要数据Model属性对应Column获取插件(ModelColumnPlugin)插件
this.tbMapper.batchInsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime);
// 或者排除某些列
this.tbMapper.batchInsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -427,6 +432,7 @@ public class Test {
项目中我们有时需要获取数据Model对应数据库字段的名称,一般直接根据数据Model的属性就可以猜出数据库对应column的名字,可是有的时候当column使用了columnOverride或者columnRenamingRule时就需要去看数据库设计了,所以提供了这个插件获取model对应的数据库Column。
* 配合Example Criteria 增强插件(ExampleEnhancedPlugin)使用,这个插件还提供了asc()和desc()方法配合Example的orderBy方法效果更佳。
* 配合批量插入插件(BatchInsertPlugin)使用,batchInsertSelective(@Param("list") List<XXX> list, @Param("selective") XXX.Column ... insertColumns)。
* 提供静态excludes方法来进行快速反选。
插件:
```xml
@@ -481,6 +487,9 @@ public class Test {
this.tbMapper.batchInsert(list);
// 下面按需插入指定列(类似于insertSelective)
this.tbMapper.batchInsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime);
// 4. excludes 方法
this.tbMapper.batchInsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -494,9 +503,14 @@ public class Test {
<plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin">
<!--
支持upsertByExample,upsertByExampleSelective操作
!需开启allowMultiQueries=true多条sql提交操作,所以不建议使用!
!需开启allowMultiQueries=true多条sql提交操作,所以不建议使用!插件默认不开启
-->
<property name="allowMultiQueries" value="true"/>
<property name="allowMultiQueries" value="false"/>
<!--
开启批量功能,支持batchUpsert,batchUpsertWithBLOBs,batchUpserSelective
!这几个方法中无法支持IncrementsPlugin的方法!插件默认不开启
-->
<property name="allowBatchUpsert" value="fasle"/>
</plugin>
```
使用:
@@ -607,6 +621,9 @@ public class Test {
.build(),
Tb.Column.field1
);
// 3. 排除某些列
this.tbMapper.insertSelective(tb, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -1075,6 +1092,15 @@ public class Test {
Tb.Column.field2
);
// 同理还有 selectByPrimaryKeySelective,selectOneByExampleSelective(SelectOneByExamplePlugin插件配合使用)方法
// 当然可以使用excludes
this.tbMapper.selectByExampleSelective(
new TbExample()
.createCriteria()
.andField1GreaterThan(1)
.example(),
Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)
);
}
}
```
+7 -2
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.2</version>
<version>1.2.5</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -85,6 +85,11 @@
<version>2.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
</dependencies>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++profiles++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -212,7 +217,7 @@
<connection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</connection>
<developerConnection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</developerConnection>
<url>https://github.com/itfsw/mybatis-generator-plugin</url>
<tag>V1.2.2</tag>
<tag>V1.2.5</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -23,8 +23,11 @@ import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* ---------------------------------------------------------------------------
@@ -37,6 +40,8 @@ import java.util.List;
public class BatchInsertPlugin extends BasePlugin {
public static final String METHOD_BATCH_INSERT = "batchInsert"; // 方法名
public static final String METHOD_BATCH_INSERT_SELECTIVE = "batchInsertSelective"; // 方法名
public static final String PRO_ALLOW_MULTI_QUERIES = "allowMultiQueries"; // property allowMultiQueries
private boolean allowMultiQueries = false; // 是否允许多sql提交
/**
* {@inheritDoc}
@@ -59,6 +64,15 @@ public class BatchInsertPlugin extends BasePlugin {
return false;
}
// 插件是否开启了多sql提交
Properties properties = this.getProperties();
String allowMultiQueries = properties.getProperty(PRO_ALLOW_MULTI_QUERIES);
this.allowMultiQueries = allowMultiQueries == null ? false : StringUtility.isTrue(allowMultiQueries);
if (this.allowMultiQueries) {
// 提示用户注意信息
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件您开启了allowMultiQueries支持,注意在jdbc url 配置中增加“allowMultiQueries=true”支持(不怎么建议使用该功能,开启多sql提交会增加sql注入的风险,请确保你所有sql都使用MyBatis书写,请不要使用statement进行sql提交)!");
}
return super.validate(warnings);
}
@@ -143,23 +157,75 @@ public class BatchInsertPlugin extends BasePlugin {
// values 构建
batchInsertEle.addElement(new TextElement("values"));
batchInsertEle.addElement(foreachElement);
if (context.getPlugins().sqlMapInsertElementGenerated(batchInsertEle, introspectedTable)) {
document.getRootElement().addElement(batchInsertEle);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsert实现方法。");
}
document.getRootElement().addElement(batchInsertEle);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsert实现方法。");
// 2. batchInsertSelective
XmlElement element = new XmlElement("insert");
element.addAttribute(new Attribute("id", METHOD_BATCH_INSERT_SELECTIVE));
// 参数类型
element.addAttribute(new Attribute("parameterType", "map"));
XmlElement batchInsertSelectiveEle = new XmlElement("insert");
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(element);
commentGenerator.addComment(batchInsertSelectiveEle);
batchInsertSelectiveEle.addAttribute(new Attribute("id", METHOD_BATCH_INSERT_SELECTIVE));
// 参数类型
batchInsertSelectiveEle.addAttribute(new Attribute("parameterType", "map"));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(element, introspectedTable);
XmlElementGeneratorTools.useGeneratedKeys(batchInsertSelectiveEle, introspectedTable);
element.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime() + " ("));
// 支持原生字段非空判断
if (this.allowMultiQueries) {
XmlElement chooseEle = new XmlElement("choose");
// selective 增强
XmlElement selectiveEnhancedEle = new XmlElement("when");
selectiveEnhancedEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
chooseEle.addElement(selectiveEnhancedEle);
selectiveEnhancedEle.getElements().addAll(this.generateSelectiveEnhancedEles(introspectedTable));
// 原生非空判断语句
XmlElement selectiveNormalEle = new XmlElement("otherwise");
chooseEle.addElement(selectiveNormalEle);
XmlElement foreachEle = new XmlElement("foreach");
selectiveNormalEle.addElement(foreachEle);
foreachEle.addAttribute(new Attribute("collection", "list"));
foreachEle.addAttribute(new Attribute("item", "item"));
foreachEle.addAttribute(new Attribute("separator", ";"));
foreachEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
XmlElement insertTrimElement = new XmlElement("trim");
foreachEle.addElement(insertTrimElement);
insertTrimElement.addElement(XmlElementGeneratorTools.generateKeysSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "item."));
foreachEle.addElement(new TextElement("values"));
XmlElement valuesTrimElement = new XmlElement("trim");
foreachEle.addElement(valuesTrimElement);
valuesTrimElement.addElement(XmlElementGeneratorTools.generateValuesSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()), "item."));
batchInsertSelectiveEle.addElement(chooseEle);
} else {
batchInsertSelectiveEle.getElements().addAll(this.generateSelectiveEnhancedEles(introspectedTable));
}
document.getRootElement().addElement(batchInsertSelectiveEle);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsertSelective实现方法。");
return true;
}
/**
* 生成insert selective 增强的插入语句
* @param introspectedTable
* @return
*/
private List<Element> generateSelectiveEnhancedEles(IntrospectedTable introspectedTable) {
List<Element> eles = new ArrayList<>();
eles.add(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime() + " ("));
XmlElement foreachInsertColumns = new XmlElement("foreach");
foreachInsertColumns.addAttribute(new Attribute("collection", "selective"));
@@ -167,12 +233,12 @@ public class BatchInsertPlugin extends BasePlugin {
foreachInsertColumns.addAttribute(new Attribute("separator", ","));
foreachInsertColumns.addElement(new TextElement("${column.value}"));
element.addElement(foreachInsertColumns);
eles.add(foreachInsertColumns);
element.addElement(new TextElement(")"));
eles.add(new TextElement(")"));
// values
element.addElement(new TextElement("values"));
eles.add(new TextElement("values"));
// foreach values
XmlElement foreachValues = new XmlElement("foreach");
@@ -203,14 +269,8 @@ public class BatchInsertPlugin extends BasePlugin {
foreachValues.addElement(new TextElement(")"));
element.addElement(foreachValues);
eles.add(foreachValues);
if (context.getPlugins().sqlMapInsertElementGenerated(element, introspectedTable)) {
document.getRootElement().addElement(element);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsertSelective实现方法。");
}
return true;
return eles;
}
}
@@ -461,12 +461,6 @@ public class LogicalDeletePlugin extends BasePlugin {
} else {
logicalDeleteValue = this.logicalDeleteValue;
}
// TODO 过期
Field field = JavaElementGeneratorTools.generateStaticFinalField("DEL_FLAG_OFF", this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalDeleteValue);
field.addAnnotation("@Deprecated");
commentGenerator.addFieldComment(field, introspectedTable);
// 常量插入到第一位
fields.add(0, field);
Field logicalDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(this.logicalDeleteConstName, this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalDeleteValue);
commentGenerator.addFieldComment(logicalDeleteConstField, introspectedTable);
@@ -485,13 +479,6 @@ public class LogicalDeletePlugin extends BasePlugin {
logicalUnDeleteValue = this.logicalUnDeleteValue;
}
// TODO 过期
Field field1 = JavaElementGeneratorTools.generateStaticFinalField("DEL_FLAG_ON", this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalUnDeleteValue);
field1.addAnnotation("@Deprecated");
commentGenerator.addFieldComment(field1, introspectedTable);
// 常量插入到第一位
fields.add(0, field1);
Field logicalUnDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(this.logicalUnDeleteConstName, this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalUnDeleteValue);
commentGenerator.addFieldComment(logicalUnDeleteConstField, introspectedTable);
fields.add(0, logicalUnDeleteConstField);
@@ -565,13 +552,6 @@ public class LogicalDeletePlugin extends BasePlugin {
method.addBodyLine(sb.toString());
FormatTools.addMethodWithBestPosition(innerClass, method);
// TODO 过期方法
Method mAndDeleted = new Method(method);
mAndDeleted.setName("andDeleted");
mAndDeleted.addAnnotation("@Deprecated");
FormatTools.addMethodWithBestPosition(innerClass, mAndDeleted);
logger.debug("itfsw(逻辑删除插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "增加andDeleted方法。");
}
}
}
@@ -34,6 +34,7 @@ import org.mybatis.generator.internal.util.JavaBeansUtil;
*/
public class ModelColumnPlugin extends BasePlugin {
public static final String ENUM_NAME = "Column"; // 内部Enum名
public static final String METHOD_EXCLUDES = "excludes"; // 方法名
/**
* Model Methods 生成
@@ -174,6 +175,28 @@ public class ModelColumnPlugin extends BasePlugin {
FormatTools.addMethodWithBestPosition(innerEnum, asc);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加asc()和desc()方法。");
// excludes
topLevelClass.addImportedType("java.util.Arrays");
topLevelClass.addImportedType(FullyQualifiedJavaType.getNewArrayListInstance());
Method mExcludes = JavaElementGeneratorTools.generateMethod(
METHOD_EXCLUDES,
JavaVisibility.PUBLIC,
new FullyQualifiedJavaType(ENUM_NAME + "[]"),
new Parameter(innerEnum.getType(), "excludes", true)
);
commentGenerator.addGeneralMethodComment(mExcludes, introspectedTable);
mExcludes.setStatic(true);
JavaElementGeneratorTools.generateMethodBody(
mExcludes,
"ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values()));",
"if (excludes != null && excludes.length > 0) {",
"columns.removeAll(new ArrayList<>(Arrays.asList(excludes)));",
"}",
"return columns.toArray(new Column[]{});"
);
FormatTools.addMethodWithBestPosition(innerEnum, mExcludes);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加excludes方法。");
return innerEnum;
}
}
@@ -41,6 +41,14 @@ public class SelectOneByExamplePlugin extends BasePlugin {
private XmlElement selectOneByExampleEle;
private XmlElement selectOneByExampleWithBLOBsEle;
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
// bug:26,27
this.selectOneByExampleWithBLOBsEle = null;
this.selectOneByExampleEle = null;
}
/**
* Java Client Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
@@ -20,10 +20,7 @@ import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.ISelectOneByExamplePluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
@@ -44,6 +41,8 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
public static final String METHOD_SELECT_BY_PRIMARY_KEY_SELECTIVE = "selectByPrimaryKeySelective";
public static final String METHOD_SELECT_ONE_BY_EXAMPLE_SELECTIVE = "selectOneByExampleSelective";
public static final String ID_FOR_PROPERTY_BASED_RESULT_MAP = "BasePropertyResultMap";
private XmlElement selectByExampleSelectiveEle;
private XmlElement selectByPrimaryKeySelectiveEle;
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
@@ -62,6 +61,19 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
return super.validate(warnings);
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param introspectedTable
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
// bug:26,27
this.selectByExampleSelectiveEle = null;
this.selectByPrimaryKeySelectiveEle = null;
}
// =========================================== client 方法生成 ===================================================
@Override
@@ -120,18 +132,24 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
// ============================================== sqlMap 生成 ===================================================
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
this.selectByExampleSelectiveEle = this.generateSelectSelectiveElement(METHOD_SELECT_BY_EXAMPLE_SELECTIVE, introspectedTable, false, true);
return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
if (!introspectedTable.hasBLOBColumns()) {
this.selectByExampleSelectiveEle = this.generateSelectSelectiveElement(METHOD_SELECT_BY_EXAMPLE_SELECTIVE, introspectedTable, false, true);
}
return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
this.selectByPrimaryKeySelectiveEle = this.generateSelectSelectiveElement(METHOD_SELECT_BY_PRIMARY_KEY_SELECTIVE, introspectedTable, false, false);
return super.sqlMapSelectByPrimaryKeyElementGenerated(element, introspectedTable);
}
@@ -156,15 +174,18 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) {
resultMapEle.addElement(XmlElementGeneratorTools.generateResultMapResultElement("result", introspectedColumn));
}
document.getRootElement().getElements().add(0, resultMapEle);
document.getRootElement().addElement(0, resultMapEle);
}
// 1. selectByExampleSelective 方法
FormatTools.addElementWithBestPosition(document.getRootElement(), this.generateSelectSelectiveElement(METHOD_SELECT_BY_EXAMPLE_SELECTIVE, introspectedTable, false, true));
if (this.selectByExampleSelectiveEle != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.selectByExampleSelectiveEle);
}
// 2. selectByPrimaryKeySelective
FormatTools.addElementWithBestPosition(document.getRootElement(), this.generateSelectSelectiveElement(METHOD_SELECT_BY_PRIMARY_KEY_SELECTIVE, introspectedTable, false, false));
if (this.selectByPrimaryKeySelectiveEle != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.selectByPrimaryKeySelectiveEle);
}
return true;
}
@@ -23,9 +23,11 @@ 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.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
@@ -42,13 +44,19 @@ public class UpsertPlugin extends BasePlugin {
public static final String METHOD_UPSERT_WITH_BLOBS = "upsertWithBLOBs"; // 方法名
public static final String METHOD_UPSERT_SELECTIVE = "upsertSelective"; // 方法名
public static final String METHOD_BATCH_UPSERT = "batchUpsert"; // 方法名
public static final String METHOD_BATCH_UPSERT_WITH_BLOBS = "batchUpsertWithBLOBs"; // 方法名
public static final String METHOD_BATCH_UPSERT_SELECTIVE = "batchUpsertSelective"; // 方法名
public static final String METHOD_UPSERT_BY_EXAMPLE = "upsertByExample"; // 方法名
public static final String METHOD_UPSERT_BY_EXAMPLE_WITH_BLOBS = "upsertByExampleWithBLOBs"; // 方法名
public static final String METHOD_UPSERT_BY_EXAMPLE_SELECTIVE = "upsertByExampleSelective"; // 方法名
public static final String PRO_ALLOW_MULTI_QUERIES = "allowMultiQueries"; // property allowMultiQueries
public static final String PRO_ALLOW_BATCH_UPSERT = "allowBatchUpsert"; // property allowBatch
private boolean allowMultiQueries = false; // 是否允许多sql提交
private boolean allowBatchUpsert = false;
/**
* {@inheritDoc}
@@ -71,6 +79,16 @@ public class UpsertPlugin extends BasePlugin {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件您开启了allowMultiQueries支持,注意在jdbc url 配置中增加“allowMultiQueries=true”支持(不怎么建议使用该功能,开启多sql提交会增加sql注入的风险,请确保你所有sql都使用MyBatis书写,请不要使用statement进行sql提交)!");
}
// 是否允许批量
String allowBatchUpsert = properties.getProperty(PRO_ALLOW_BATCH_UPSERT);
this.allowBatchUpsert = allowBatchUpsert == null ? false : StringUtility.isTrue(allowBatchUpsert);
// 批量时依赖插件 ModelColumnPlugin
if (this.allowBatchUpsert && !PluginTools.checkDependencyPlugin(context, ModelColumnPlugin.class)) {
// 提示用户注意信息
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件您开启了allowBatchUpsert支持,请配置依赖的插件" + ModelColumnPlugin.class.getTypeName() + "!");
}
return super.validate(warnings);
}
@@ -108,7 +126,7 @@ public class UpsertPlugin extends BasePlugin {
commentGenerator.addGeneralMethodComment(mUpsertWithBLOBs, introspectedTable);
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mUpsertWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsert方法。");
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertWithBLOBs方法。");
}
// ====================================== upsertSelective ======================================
@@ -155,7 +173,7 @@ public class UpsertPlugin extends BasePlugin {
commentGenerator.addGeneralMethodComment(mUpsertByExampleWithBLOBs, introspectedTable);
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mUpsertByExampleWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExample方法。");
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExampleWithBLOBs方法。");
}
// ====================================== upsertByExampleSelective ======================================
@@ -175,6 +193,55 @@ public class UpsertPlugin extends BasePlugin {
}
}
if (this.allowBatchUpsert) {
// ====================================== batchUpsert ======================================
FullyQualifiedJavaType returnType = FullyQualifiedJavaType.getNewListInstance();
returnType.addTypeArgument(JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable));
Method mBatchUpsert = JavaElementGeneratorTools.generateMethod(
METHOD_BATCH_UPSERT,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(returnType, "list", "@Param(\"list\")")
);
commentGenerator.addGeneralMethodComment(mBatchUpsert, introspectedTable);
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mBatchUpsert);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加batchUpsert方法。");
// ====================================== batchUpsertWithBLOBs ======================================
// !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()) {
returnType = FullyQualifiedJavaType.getNewListInstance();
returnType.addTypeArgument(JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable));
Method mBatchUpsertWithBLOBs = JavaElementGeneratorTools.generateMethod(
METHOD_BATCH_UPSERT_WITH_BLOBS,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(returnType, "list", "@Param(\"list\")")
);
commentGenerator.addGeneralMethodComment(mBatchUpsertWithBLOBs, introspectedTable);
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mBatchUpsertWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加batchUpsertWithBLOBs方法。");
}
// ====================================== batchUpsertSelective ======================================
returnType = FullyQualifiedJavaType.getNewListInstance();
returnType.addTypeArgument(fullFieldModel);
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(introspectedTable.getRules().calculateAllFieldsClass().getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
Method mBatchUpsertSelective = JavaElementGeneratorTools.generateMethod(
METHOD_BATCH_UPSERT_SELECTIVE,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(returnType, "list", "@Param(\"list\")"),
new Parameter(selectiveType, "selective", "@Param(\"selective\")", true)
);
commentGenerator.addGeneralMethodComment(mBatchUpsertSelective, introspectedTable);
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mBatchUpsertSelective);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加batchUpsertSelective方法。");
}
return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
}
@@ -193,9 +260,147 @@ public class UpsertPlugin extends BasePlugin {
this.generateXmlElement(document, introspectedTable, true);
}
if (this.allowBatchUpsert) {
this.generateBatchXmlElementSelective(document, introspectedTable);
this.generateBatchXmlElement(document, introspectedTable, false);
if (introspectedTable.hasBLOBColumns()) {
this.generateBatchXmlElement(document, introspectedTable, true);
}
}
return super.sqlMapDocumentGenerated(document, introspectedTable);
}
/**
* 批量
* @param document
* @param introspectedTable
*/
private void generateBatchXmlElementSelective(Document document, IntrospectedTable introspectedTable) {
XmlElement insertEle = new XmlElement("insert");
insertEle.addAttribute(new Attribute("id", METHOD_BATCH_UPSERT_SELECTIVE));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(insertEle);
// 参数类型
insertEle.addAttribute(new Attribute("parameterType", "map"));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(insertEle, introspectedTable);
// insert
insertEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime() + " ("));
XmlElement foreachInsertColumns = new XmlElement("foreach");
foreachInsertColumns.addAttribute(new Attribute("collection", "selective"));
foreachInsertColumns.addAttribute(new Attribute("item", "column"));
foreachInsertColumns.addAttribute(new Attribute("separator", ","));
foreachInsertColumns.addElement(new TextElement("${column.value}"));
insertEle.addElement(foreachInsertColumns);
insertEle.addElement(new TextElement(")"));
// values
insertEle.addElement(new TextElement("values"));
// foreach values
XmlElement foreachValues = new XmlElement("foreach");
foreachValues.addAttribute(new Attribute("collection", "list"));
foreachValues.addAttribute(new Attribute("item", "item"));
foreachValues.addAttribute(new Attribute("separator", ","));
foreachValues.addElement(new TextElement("("));
// foreach 所有插入的列,比较是否存在
XmlElement foreachInsertColumnsCheck = new XmlElement("foreach");
foreachInsertColumnsCheck.addAttribute(new Attribute("collection", "selective"));
foreachInsertColumnsCheck.addAttribute(new Attribute("item", "column"));
foreachInsertColumnsCheck.addAttribute(new Attribute("separator", ","));
// 所有表字段
List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
List<IntrospectedColumn> columns1 = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
for (int i = 0; i < columns1.size(); i++) {
IntrospectedColumn introspectedColumn = columns.get(i);
XmlElement check = new XmlElement("if");
check.addAttribute(new Attribute("test", "'" + introspectedColumn.getActualColumnName() + "' == column.value"));
check.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "item.")));
foreachInsertColumnsCheck.addElement(check);
}
foreachValues.addElement(foreachInsertColumnsCheck);
foreachValues.addElement(new TextElement(")"));
insertEle.addElement(foreachValues);
insertEle.addElement(new TextElement("on duplicate key update "));
// set
XmlElement foreachSetColumns = new XmlElement("foreach");
insertEle.addElement(foreachSetColumns);
foreachSetColumns.addAttribute(new Attribute("collection", "selective"));
foreachSetColumns.addAttribute(new Attribute("item", "column"));
foreachSetColumns.addAttribute(new Attribute("separator", ","));
foreachSetColumns.addElement(new TextElement("${column.value} = values(${column.value})"));
document.getRootElement().addElement(insertEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchUpsertSelective实现方法。");
}
/**
* 批量
* @param document
* @param introspectedTable
* @param withBLOBs
*/
private void generateBatchXmlElement(Document document, IntrospectedTable introspectedTable, boolean withBLOBs) {
List<IntrospectedColumn> columns = ListUtilities.removeGeneratedAlwaysColumns(withBLOBs ? introspectedTable.getAllColumns() : introspectedTable.getNonBLOBColumns());
XmlElement insertEle = new XmlElement("insert");
insertEle.addAttribute(new Attribute("id", withBLOBs ? METHOD_BATCH_UPSERT_WITH_BLOBS : METHOD_BATCH_UPSERT));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(insertEle);
// 参数类型
insertEle.addAttribute(new Attribute("parameterType", "map"));
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(insertEle, introspectedTable);
// insert
insertEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
for (Element element : XmlElementGeneratorTools.generateUpsertKeys(columns, null)) {
insertEle.addElement(element);
}
insertEle.addElement(new TextElement("values"));
// values
XmlElement foreachEle = new XmlElement("foreach");
insertEle.addElement(foreachEle);
foreachEle.addAttribute(new Attribute("collection", "list"));
foreachEle.addAttribute(new Attribute("item", "item"));
foreachEle.addAttribute(new Attribute("separator", ","));
for (Element element : XmlElementGeneratorTools.generateUpsertValues(columns, "item.", true)) {
foreachEle.addElement(element);
}
insertEle.addElement(new TextElement("on duplicate key update "));
// set
Iterator<IntrospectedColumn> columnIterator = columns.iterator();
while (columnIterator.hasNext()) {
IntrospectedColumn column = columnIterator.next();
insertEle.addElement(new TextElement(
MyBatis3FormattingUtilities.getEscapedColumnName(column)
+ " = values(" + MyBatis3FormattingUtilities.getEscapedColumnName(column)
+ ")"
+ (columnIterator.hasNext() ? "," : "")
));
}
document.getRootElement().addElement(insertEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加" + (withBLOBs ? "batchUpsertWithBLOBs" : "batchUpsert") + "实现方法。");
}
/**
* 当Selective情况
* @param document
@@ -315,7 +520,7 @@ public class UpsertPlugin extends BasePlugin {
}
document.getRootElement().addElement(insertEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsert实现方法。");
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加" + (withBLOBs ? "upsertWithBLOBs" : "upsert") + "实现方法。");
if (this.allowMultiQueries) {
// ====================================== upsertByExample ======================================
@@ -352,7 +557,7 @@ public class UpsertPlugin extends BasePlugin {
this.generateExistsClause(introspectedTable, updateEle, XmlElementGeneratorTools.generateUpsertValues(columns, "record.", false));
document.getRootElement().addElement(updateEle);
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加upsertByExample实现方法。");
logger.debug("itfsw(存在即更新插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加" + (withBLOBs ? "upsertByExampleWithBLOBs" : "upsertByExample") + "实现方法。");
}
}
@@ -66,6 +66,11 @@ public class BatchInsertPluginTest {
Assert.assertTrue(tool.getWarnings().size() == 2);
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.BatchInsertPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
// 2. 普通提示
tool = MyBatisGeneratorTool.create("scripts/BatchInsertPlugin/mybatis-generator-with-allowMultiQueries.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.BatchInsertPlugin插件您开启了allowMultiQueries支持,注意在jdbc url 配置中增加“allowMultiQueries=true”支持(不怎么建议使用该功能,开启多sql提交会增加sql注入的风险,请确保你所有sql都使用MyBatis书写,请不要使用statement进行sql提交)!");
}
/**
@@ -142,7 +147,7 @@ public class BatchInsertPluginTest {
@Test
public void testBatchInsert() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/BatchInsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
tool.generate(() -> DBHelper.resetDB("scripts/BatchInsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试sql
@@ -164,6 +169,11 @@ public class BatchInsertPluginTest {
// 2. 执行sql
Object count = tbMapper.invoke("batchInsert", params);
Assert.assertEquals(count, 2);
for (int i = 0; i < params.size(); i++) {
ObjectUtil item = new ObjectUtil(params.get(i));
Assert.assertEquals(item.get("id"), 1L + i);
}
}
});
}
@@ -174,7 +184,7 @@ public class BatchInsertPluginTest {
@Test
public void testBatchInsertSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/BatchInsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
tool.generate(() -> DBHelper.resetDB("scripts/BatchInsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试sql
@@ -204,4 +214,50 @@ public class BatchInsertPluginTest {
}
});
}
/**
* 测试开启 AllowMultiQueries 支持
*/
@Test
public void testAllowMultiQueries() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/BatchInsertPlugin/mybatis-generator-with-allowMultiQueries.xml");
// 1. 测试增强的selective
tool.generate(() -> DBHelper.resetDB("scripts/BatchInsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
List<Object> params = new ArrayList<>();
params.add(new ObjectUtil(loader, packagz + ".Tb").set("field1", "test").getObject());
params.add(new ObjectUtil(loader, packagz + ".Tb").set("field1", "test").set("field2", 1).getObject());
ObjectUtil columnField2 = new ObjectUtil(loader, packagz + ".Tb$Column#field2");
Object columns = Array.newInstance(columnField2.getCls(), 1);
Array.set(columns, 0, columnField2.getObject());
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "batchInsertSelective", params, columns);
Assert.assertEquals(sql, "insert into tb ( field2 ) values ( null ) , ( 1 )");
// 2. 执行sql
Object count = tbMapper.invoke("batchInsertSelective", params, columns);
Assert.assertEquals(count, 2);
}
});
// 2. 测试原生非空判断
tool.generate(() -> DBHelper.resetDB("scripts/BatchInsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
List<Object> params = new ArrayList<>();
params.add(new ObjectUtil(loader, packagz + ".Tb").set("field1", "test").getObject());
params.add(new ObjectUtil(loader, packagz + ".Tb").set("field1", "test").set("field2", 1).getObject());
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "batchInsertSelective", params, null);
Assert.assertEquals(sql, "insert into tb ( field1 ) values ( 'test' ) ; insert into tb ( field1, field2 ) values ( 'test', 1 )");
// 2. 执行sql
Object count = tbMapper.invoke("batchInsertSelective", params, null);
Assert.assertTrue((int) count > 0);
}
});
}
}
@@ -141,7 +141,7 @@ public class LogicalDeletePluginTest {
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andDeleted", true);
criteria.invoke("andLogicalDeleted", true);
criteria.invoke("andIdEqualTo", 3l);
@@ -16,16 +16,15 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.AbstractShellCallback;
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool;
import com.itfsw.mybatis.generator.plugins.tools.ObjectUtil;
import com.itfsw.mybatis.generator.plugins.tools.*;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Array;
import java.sql.SQLException;
/**
@@ -41,7 +40,7 @@ public class ModelColumnPluginTest {
* 初始化数据库
*/
@BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException {
public static void init() throws SQLException, IOException {
DBHelper.createDB("scripts/ModelColumnPlugin/init.sql");
}
@@ -49,7 +48,7 @@ public class ModelColumnPluginTest {
* 测试生成的model
*/
@Test
public void test() throws Exception {
public void testModel() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ModelColumnPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
@@ -78,6 +77,63 @@ public class ModelColumnPluginTest {
Assert.assertEquals(TbKeysColumnKey1.invoke("value"), "key_1");
ObjectUtil TbKeysColumnField1 = new ObjectUtil(loader, packagz + ".TbKeys$Column#field1");
Assert.assertEquals(TbKeysColumnField1.invoke("value"), "field_1");
// 5. excludes 方法
// 不排除
Object columns = Array.newInstance(TbColumnField1.getCls(), 0);
Object[] result = (Object[])(MethodUtils.invokeStaticMethod(Class.forName(packagz + ".Tb$Column"), "excludes", columns));
Assert.assertEquals(result.length, 5);
// 排除两个
columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject());
result = (Object[])(MethodUtils.invokeStaticMethod(Class.forName(packagz + ".Tb$Column"), "excludes", columns));
Assert.assertEquals(result.length, 3);
for (Object obj : result){
ObjectUtil column = new ObjectUtil(obj);
if (column.invoke("value").equals("field_1") || column.invoke("value").equals("inc_f2")){
Assert.assertTrue(false);
}
}
}
});
}
/**
* 测试excludes
*/
@Test
public void testExcludes() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ModelColumnPlugin/mybatis-generator-with-SeleciveEnhancedPlugin.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", 121L);
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());
// sql(指定列)
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( id , field_1 , inc_f2 ) values ( 121 , 'null' , 5 )");
// sql(排除列)
columns = MethodUtils.invokeStaticMethod(Class.forName(packagz + ".Tb$Column"), "excludes", columns);
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( inc_f1 , inc_f3 ) values ( null , 10 )");
Object result = tbMapper.invoke("insertSelective", tb.getObject(), columns);
Assert.assertEquals(result, 1);
}
});
}
@@ -25,8 +25,11 @@ import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
@@ -41,7 +44,7 @@ public class UpsertPluginTest {
* 初始化
*/
@BeforeClass
public static void init() throws Exception{
public static void init() throws Exception {
DBHelper.createDB("scripts/UpsertPlugin/init.sql");
}
@@ -421,4 +424,136 @@ public class UpsertPluginTest {
}
});
}
/**
* 测试批量batchUpsert
*/
@Test
public void testBatchUpsert() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator-with-allowBatchUpsert.xml");
tool.generate(() -> DBHelper.resetDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
List<Object> params = new ArrayList<>();
params.add(new ObjectUtil(loader, packagz + ".Tb").set("id", 1L).set("field1", "ts1").getObject());
params.add(new ObjectUtil(loader, packagz + ".Tb").set("id", 6L).set("field1", "ts2").set("field2", 1).getObject());
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "batchUpsert", params);
Assert.assertEquals(sql, "insert into tb (id, field1, field2) values (1, 'ts1', null ) , (6, 'ts2', 1 ) on duplicate key update id = values(id), field1 = values(field1), field2 = values(field2)");
// 2. 执行sql
Object count = tbMapper.invoke("batchUpsert", params);
Assert.assertEquals(count, 3);
// 验证
ResultSet rs = DBHelper.execute(sqlSession, "select * from tb where id = 1");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts1");
rs = DBHelper.execute(sqlSession, "select * from tb where id = 6");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts2");
}
});
}
/**
* 测试批量batchUpsertWithBLOBs
*/
@Test
public void testBatchUpsertWithBLOBs() throws Exception {
// 1. batchUpsert
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator-with-allowBatchUpsert.xml");
tool.generate(() -> DBHelper.resetDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbBlobsMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbBlobsMapper")));
List<Object> params = new ArrayList<>();
params.add(new ObjectUtil(loader, packagz + ".TbBlobs").set("id", 1L).set("field1", "ts1").getObject());
params.add(new ObjectUtil(loader, packagz + ".TbBlobs").set("id", 6L).set("field1", "ts2").getObject());
String sql = SqlHelper.getFormatMapperSql(tbBlobsMapper.getObject(), "batchUpsert", params);
Assert.assertEquals(sql, "insert into tb_blobs (id, field1) values (1, 'ts1') , (6, 'ts2') on duplicate key update id = values(id), field1 = values(field1)");
// 2. 执行sql
Object count = tbBlobsMapper.invoke("batchUpsert", params);
Assert.assertEquals(count, 3);
// 验证
ResultSet rs = DBHelper.execute(sqlSession, "select * from tb_blobs where id = 1");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts1");
rs = DBHelper.execute(sqlSession, "select * from tb_blobs where id = 6");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts2");
}
});
// 2. batchUpsertWithBLOBs
tool.generate(() -> DBHelper.resetDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbBlobsMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbBlobsMapper")));
List<Object> params = new ArrayList<>();
params.add(new ObjectUtil(loader, packagz + ".TbBlobsWithBLOBs").set("id", 1L).set("field1", "ts1").set("field3", "ff1").getObject());
params.add(new ObjectUtil(loader, packagz + ".TbBlobsWithBLOBs").set("id", 6L).set("field1", "ts2").set("field3", "ff2").getObject());
String sql = SqlHelper.getFormatMapperSql(tbBlobsMapper.getObject(), "batchUpsertWithBLOBs", params);
Assert.assertEquals(sql, "insert into tb_blobs (id, field1, field2, field3) values (1, 'ts1', 'null', 'ff1') , (6, 'ts2', 'null', 'ff2') on duplicate key update id = values(id), field1 = values(field1), field2 = values(field2), field3 = values(field3)");
// 2. 执行sql
Object count = tbBlobsMapper.invoke("batchUpsertWithBLOBs", params);
Assert.assertEquals(count, 3);
// 验证
ResultSet rs = DBHelper.execute(sqlSession, "select * from tb_blobs where id = 1");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts1");
Assert.assertEquals(rs.getString("field3"), "ff1");
rs = DBHelper.execute(sqlSession, "select * from tb_blobs where id = 6");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts2");
Assert.assertEquals(rs.getString("field3"), "ff2");
}
});
}
/**
* 测试批量batchUpsertSelective
*/
@Test
public void testBatchUpsertSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator-with-allowBatchUpsert.xml");
tool.generate(() -> DBHelper.resetDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
List<Object> params = new ArrayList<>();
params.add(new ObjectUtil(loader, packagz + ".Tb").set("id", 1L).set("field1", "ts1").getObject());
params.add(new ObjectUtil(loader, packagz + ".Tb").set("id", 6L).set("field1", "ts2").set("field2", 1).getObject());
ObjectUtil columnId = new ObjectUtil(loader, packagz + ".Tb$Column#id");
ObjectUtil columnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
Object columns = Array.newInstance(columnId.getCls(), 2);
Array.set(columns, 0, columnId.getObject());
Array.set(columns, 1, columnField1.getObject());
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "batchUpsertSelective", params, columns);
Assert.assertEquals(sql, "insert into tb ( id , field1 ) values ( 1 , 'ts1' ) , ( 6 , 'ts2' ) on duplicate key update id = values(id) , field1 = values(field1)");
// 2. 执行sql
Object count = tbMapper.invoke("batchUpsertSelective", params, columns);
Assert.assertEquals(count, 3);
// 验证
ResultSet rs = DBHelper.execute(sqlSession, "select * from tb where id = 1");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts1");
rs = DBHelper.execute(sqlSession, "select * from tb where id = 6");
rs.first();
Assert.assertEquals(rs.getString("field1"), "ts2");
Assert.assertNull(rs.getString("field2"));
}
});
}
}
@@ -24,7 +24,7 @@ CREATE TABLE `tb` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -40,7 +40,7 @@ CREATE TABLE `tb_blobs` (
`field2` longtext COMMENT '注释2',
`field3` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -56,7 +56,7 @@ CREATE TABLE `tb_keys` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int DEFAULT NULL,
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -71,7 +71,7 @@ CREATE TABLE `tb_single_blob` (
`field1` longtext COMMENT '注释2',
`field2` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
@@ -0,0 +1,64 @@
<?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.BatchInsertPlugin">
<property name="allowMultiQueries" value="true"/>
</plugin>
<!-- 数据Model属性对应Column获取插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys" />
<table tableName="tb_single_blob">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_blobs">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
@@ -23,4 +23,4 @@ CREATE TABLE `tb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
) ENGINE=MyISAM;
@@ -26,7 +26,7 @@ CREATE TABLE `tb` (
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -49,7 +49,7 @@ CREATE TABLE `tb_blobs` (
`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;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -72,7 +72,7 @@ CREATE TABLE `tb_keys` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -93,7 +93,7 @@ CREATE TABLE `tb_single_blob` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
@@ -112,7 +112,7 @@ CREATE TABLE `tb_key_word` (
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`update` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_key_word
@@ -28,7 +28,7 @@ CREATE TABLE `tb` (
`ts_3` float DEFAULT NULL,
`ts_4` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -26,7 +26,7 @@ CREATE TABLE `tb` (
`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;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -45,7 +45,7 @@ CREATE TABLE `tb_blobs` (
`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;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -64,7 +64,7 @@ CREATE TABLE `tb_keys` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -83,7 +83,7 @@ CREATE TABLE `tb_keys_blobs` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -20,13 +20,13 @@ SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
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',
`id` bigint(20) AUTO_INCREMENT COMMENT '注释1',
`field_1` varchar(255) COMMENT '注释2',
`inc_f1` bigint(20) DEFAULT '0',
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -45,7 +45,7 @@ CREATE TABLE `tb_blobs` (
`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;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -64,7 +64,7 @@ CREATE TABLE `tb_keys` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`key_1`,`key_2`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -0,0 +1,54 @@
<?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>
@@ -26,7 +26,7 @@ CREATE TABLE `tb` (
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -49,7 +49,7 @@ CREATE TABLE `tb_blobs` (
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -72,7 +72,7 @@ CREATE TABLE `tb_keys` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -93,7 +93,7 @@ CREATE TABLE `tb_single_blob` (
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
@@ -112,7 +112,7 @@ CREATE TABLE `tb_key_word` (
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`update` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_key_word
@@ -24,7 +24,7 @@ CREATE TABLE `tb` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -43,7 +43,7 @@ CREATE TABLE `tb_blobs` (
`field2` longtext COMMENT '注释2',
`field3` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -60,7 +60,7 @@ CREATE TABLE `tb_keys` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -24,7 +24,7 @@ CREATE TABLE `tb` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -44,7 +44,7 @@ CREATE TABLE `tb_blobs` (
`field2` longtext COMMENT '注释2',
`field3` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
@@ -64,7 +64,7 @@ CREATE TABLE `tb_keys` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -82,7 +82,7 @@ CREATE TABLE `tb_single_blob` (
`field1` longtext COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
@@ -26,7 +26,7 @@ CREATE TABLE `tb` (
`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;
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -24,7 +24,7 @@ CREATE TABLE `tb` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
@@ -43,11 +43,14 @@ CREATE TABLE `tb_blobs` (
`field2` longtext COMMENT '注释2',
`field3` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
-- ----------------------------
INSERT INTO `tb_blobs` VALUES ('1', 'fd1', null, 'KK1');
INSERT INTO `tb_blobs` VALUES ('2', null, '2', null);
INSERT INTO `tb_blobs` VALUES ('3', 'fd3', '3', 'KK3');
-- ----------------------------
-- Table structure for tb_keys
@@ -59,7 +62,7 @@ CREATE TABLE `tb_keys` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
@@ -77,7 +80,7 @@ CREATE TABLE `tb_single_blob` (
`field1` longtext COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
@@ -92,7 +95,7 @@ CREATE TABLE `tb_with_inc_id` (
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for tb_with_inc_id
-- ----------------------------
@@ -107,7 +110,7 @@ CREATE TABLE `tb_blobs_with_inc_id` (
`field2` longtext COMMENT '注释3',
`field3` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for tb_blobs_with_inc_id
-- ----------------------------
@@ -0,0 +1,57 @@
<?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="allowBatchUpsert" value="true"/>
</plugin>
<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"/>
<table tableName="tb_keys"/>
<table tableName="tb_single_blob"/>
<table tableName="tb_blobs"/>
<table tableName="tb_with_inc_id">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_blobs_with_inc_id">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>