Compare commits

...
34 Commits
Author SHA1 Message Date
hewei b48c5c4195 [maven-release-plugin] prepare release V1.2.6 2018-05-28 17:54:13 +08:00
hewei 0a94a3d811 TableRenameConfigurationPlugin 2018-05-28 17:53:19 +08:00
hewei 7d266d192d TableRenameConfigurationPlugin 2018-05-28 17:52:32 +08:00
hewei b25c6806c7 Merge branch 'master' of https://github.com/itfsw/mybatis-generator-plugin 2018-05-28 17:50:44 +08:00
hewei 72f254b018 [maven-release-plugin] prepare release V1.2.6 2018-05-28 17:49:11 +08:00
hewei 0f5547a23d TableRenameConfigurationPlugin 2018-05-28 17:48:15 +08:00
hewei 4031668d26 [maven-release-plugin] prepare release V1.2.6 2018-05-28 17:39:54 +08:00
hewei 464959ef55 TableRenameConfigurationPlugin 2018-05-28 17:33:06 +08:00
hewei 074576f60e 官方domainObjectRenamingRule的bug修复 2018-05-28 17:14:29 +08:00
hewei abc2ef16b0 TableRenameConfigurationPlugin 2018-05-28 16:35:49 +08:00
hewei 2878b98290 TableConfigurationPlugin 测试用例 2018-05-28 15:59:00 +08:00
hewei 2b326a2fe3 TableConfigurationPlugin 测试用例 2018-05-28 15:49:35 +08:00
hewei 87519edc0e TableConfigurationPlugin 测试用例 2018-05-28 15:17:33 +08:00
hewei e0614069be TableConfigurationPlugin 测试用例 2018-05-28 14:37:54 +08:00
何伟 f29a30179e Update README.md 2018-05-28 09:22:55 +08:00
何伟 3e1c68a5b7 分页插件文档 2018-05-28 09:22:03 +08:00
hewei caa5144db0 TableConfigurationPlugin 2018-05-22 16:52:38 +08:00
何伟 8588c99189 过期两个插件TablePrefixPlugin、TableRenamePlugin,新版官方已提供domainObjectRenamingRule支持 2018-05-22 11:35:42 +08:00
hewei 6c832e4981 V1.2.5 2018-05-18 11:39:08 +08:00
hewei 2c41fd735e [maven-release-plugin] prepare for next development iteration 2018-05-18 11:23:43 +08:00
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
42 changed files with 2063 additions and 114 deletions
+133 -11
View File
@@ -16,13 +16,14 @@
* [数据Model属性对应Column获取插件(ModelColumnPlugin)](#8-数据model属性对应column获取插件)
* [存在即更新插件(UpsertPlugin)](#9-存在即更新插件)
* [Selective选择插入更新增强插件(SelectiveEnhancedPlugin)](#10-selective选择插入更新增强插件)
* [Table增加前缀插件(TablePrefixPlugin)](#11-table增加前缀插件)
* [Table重命名插件(TableRenamePlugin)](#12-table重命名插件)
* [~~Table增加前缀插件(TablePrefixPlugin)~~](#11-table增加前缀插件)
* [~~Table重命名插件(TableRenamePlugin)~~](#12-table重命名插件)
* [自定义注释插件(CommentPlugin)](#13-自定义注释插件)
* [增量插件(IncrementsPlugin)](#14-增量插件)
* [查询结果选择性返回插件(SelectSelectivePlugin)](#15-查询结果选择性返回插件)
* [~~官方ConstructorBased配置BUG临时修正插件(ConstructorBasedBugFixPlugin)~~](#16-官方constructorbased配置bug临时修正插件)
* [乐观锁插件(OptimisticLockerPlugin)](#17-乐观锁插件)
* [表重命名配置插件(TableConfigurationPlugin)](#18-表重命名配置插件)
---------------------------------------
Maven引用:
@@ -30,7 +31,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.2</version>
<version>1.2.5</version>
</dependency>
```
---------------------------------------
@@ -96,6 +97,8 @@ public interface TbMapper {
```
### 2. MySQL分页插件
对应表Example类增加了Mysql分页方法,limit(Integer rows)、limit(Integer offset, Integer rows)和page(Integer page, Integer pageSize)
>warning:分页从0开始,目前网上流行的大多数前端框架分页都是从0开始,插件保持这种方式;
插件:
```xml
<!-- MySQL分页插件 -->
@@ -311,14 +314,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 +352,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 +435,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 +490,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 +506,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>
```
使用:
@@ -523,6 +540,7 @@ public class Test {
tb1.setField2("xx1");
int k3 = this.tbMapper.upsertSelective(tb1);
// --------------------------------- allowMultiQueries=true ------------------------------
// 4. 开启allowMultiQueries后增加upsertByExample,upsertByExampleSelective但强力建议不要使用(需保证团队没有使用statement提交sql,否则会存在sql注入风险)
Tb tb2 = new Tb.Builder()
.field1(1)
@@ -554,6 +572,28 @@ public class Test {
.delFlag(Tb.DEL_FLAG_ON)
.build();
int k6 = this.tbMapper.upsertWithBLOBs(tb);
// --------------------------------- allowBatchUpsert=true ------------------------------
List<Tb> list = new ArrayList<>();
list.add(
new Tb.Builder()
.field1(0)
.field2("xx0")
.field3(0)
.field4(new Date())
.build()
);
list.add(
new Tb.Builder()
.field1(1)
.field2("xx1")
.field3(1)
.field4(new Date())
.build()
);
this.tbMapper.batchUpsert(list); // 对于BLOBs 有batchUpsertWithBLOBs方法
this.tbMapper.batchUpsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime);
this.tbMapper.batchUpsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)); // 排除某些列
}
}
```
@@ -607,6 +647,9 @@ public class Test {
.build(),
Tb.Column.field1
);
// 3. 排除某些列
this.tbMapper.insertSelective(tb, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -614,7 +657,12 @@ public class Test {
项目中有时会遇到配置多数据源对应多业务的情况,这种情况下可能会出现不同数据源出现重复表名,造成异常冲突。
该插件允许为表增加前缀,改变最终生成的Model、Mapper、Example类名以及xml名。
>warning: 使用[Table重命名插件](12-table重命名插件)可以实现相同功能!
>warning: 官方最新版本中已提供domainObjectRenamingRule支持(可以配合[表重命名配置插件](#18-表重命名配置插件)进行全局配置)!
```xml
<table tableName="tb">
<domainObjectRenamingRule searchString="^" replaceString="DB1" />
</table>
```
插件:
```xml
<xml>
@@ -658,6 +706,12 @@ public class Test {
<property name="searchString" value="^"/>
<property name="replaceString" value="DB1"/>
```
>warning: 官方最新版本中已提供domainObjectRenamingRule支持(可以配合[表重命名配置插件](#18-表重命名配置插件)进行全局配置)!
```xml
<table tableName="tb">
<domainObjectRenamingRule searchString="^T" replaceString="" />
</table>
```
插件:
```xml
@@ -1075,6 +1129,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)
);
}
}
```
@@ -1155,4 +1218,63 @@ public class Test {
// 对应生成的Sql: update tb set version = 1525773888559, field1 = 'ts1' where version = 100 and id = 102
}
}
```
### 18. 表重命名配置插件
官方提供了domainObjectRenamingRule(官方最新版本已提供)、columnRenamingRule分别进行生成的表名称和对应表字段的重命名支持,但是它需要每个表单独进行配置,对于常用的如表附带前缀“t_”、字段前缀“f_”这种全局性替换会比较麻烦。
该插件提供了一种全局替换机制,当表没有单独指定domainObjectRenamingRule、columnRenamingRule时采用全局性配置。同时该插件会修复官方domainObjectRenamingRule的bug(没有进行正确的首字母大写)。
同时插件提供clientSuffix、exampleSuffix、modelSuffix来修改对应生成的类和文件的结尾(之前issue中有用户希望能把Mapper替换成Dao)。
- 全局domainObjectRenamingRule
```xml
<xml>
<!-- 表重命名配置插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.TableRenameConfigurationPlugin">
<property name="domainObjectRenamingRule.searchString" value="^T"/>
<property name="domainObjectRenamingRule.replaceString" value=""/>
</plugin>
<table tableName="tb">
<!-- 这里可以禁用全局domainObjectRenamingRule配置 -->
<property name="domainObjectRenamingRule.disable" value="true"/>
</table>
<table tableName="tb_ts1">
<!-- 当然你也可以使用官方domainObjectRenamingRule的配置来覆盖全局配置 -->
<domainObjectRenamingRule searchString="^Tb" replaceString="B"/>
</table>
</xml>
```
- 全局columnRenamingRule
```xml
<xml>
<!-- 表重命名配置插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.TableRenameConfigurationPlugin">
<!-- 需要注意,这里的正则和官方一样是比对替换都是原始表的column名称 -->
<property name="columnRenamingRule.searchString" value="^f_"/>
<property name="columnRenamingRule.replaceString" value="_"/>
</plugin>
<table tableName="tb">
<!-- 这里可以禁用全局columnRenamingRule配置 -->
<property name="columnRenamingRule.disable" value="true"/>
</table>
<table tableName="tb_ts1">
<!-- 当然你也可以使用官方domainObjectRenamingRule的配置来覆盖全局配置 -->
<columnRenamingRule searchString="^f_" replaceString="_"/>
</table>
</xml>
```
- clientSuffix、exampleSuffix、modelSuffix
```xml
<xml>
<!-- 表重命名配置插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.TableRenameConfigurationPlugin">
<!-- TbMapper --> TbDao, TbMapper.xml --> TbDao.xml -->
<property name="clientSuffix" value="Dao"/>
<!-- TbExmaple --> TbQuery -->
<property name="exampleSuffix" value="Query"/>
<!-- Tb --> TbEntity -->
<property name="modelSuffix" value="Entity"/>
</plugin>
</xml>
```
+7 -2
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.3</version>
<version>1.2.6</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.3</tag>
<tag>V1.2.6</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;
}
}
@@ -61,6 +61,7 @@ public class ExampleTargetPlugin extends BasePlugin {
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
String exampleType = introspectedTable.getExampleType();
// 修改包名
Context context = getContext();
@@ -75,6 +75,7 @@ public class LogicalDeletePlugin extends BasePlugin {
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
// 1. 首先获取全局配置
Properties properties = getProperties();
String logicalDeleteColumn = properties.getProperty(PRO_LOGICAL_DELETE_COLUMN);
@@ -461,12 +462,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 +480,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 +553,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;
}
}
@@ -59,6 +59,7 @@ public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderP
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
sqlMaps.put(introspectedTable, new ArrayList<>());
// 读取并验证版本列
@@ -31,6 +31,7 @@ import java.util.List;
* @time:2017/5/18 13:54
* ---------------------------------------------------------------------------
*/
@Deprecated
public class TablePrefixPlugin extends BasePlugin {
public static final String PRO_PREFIX = "prefix"; // 前缀 property
@@ -78,5 +79,6 @@ public class TablePrefixPlugin extends BasePlugin {
logger.error("itfsw:插件" + this.getClass().getTypeName() + "使用prefix替换时异常!", e);
}
}
super.initialized(introspectedTable);
}
}
@@ -0,0 +1,258 @@
/*
* Copyright (c) 2018.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.BeanUtils;
import com.itfsw.mybatis.generator.plugins.utils.hook.ITableConfigurationHook;
import org.mybatis.generator.api.FullyQualifiedTable;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.config.ColumnRenamingRule;
import org.mybatis.generator.config.DomainObjectRenamingRule;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.mybatis.generator.internal.util.JavaBeansUtil.getCamelCaseString;
import static org.mybatis.generator.internal.util.JavaBeansUtil.getValidPropertyName;
import static org.mybatis.generator.internal.util.StringUtility.isTrue;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/5/21 11:23
* ---------------------------------------------------------------------------
*/
public class TableRenameConfigurationPlugin extends BasePlugin implements ITableConfigurationHook {
public static final String PRO_TABLE_SEARCH_STRING = "domainObjectRenamingRule.searchString"; // 查找 property
public static final String PRO_TABLE_REPLACE_STRING = "domainObjectRenamingRule.replaceString"; // 替换 property
public static final String PRO_TABLE_REPLACE_DISABLE = "domainObjectRenamingRule.disable"; // 替换 property
public static final String PRO_COLUMN_SEARCH_STRING = "columnRenamingRule.searchString"; // 查找 property
public static final String PRO_COLUMN_REPLACE_STRING = "columnRenamingRule.replaceString"; // 替换 property
public static final String PRO_COLUMN_REPLACE_DISABLE = "columnRenamingRule.disable"; // 替换 property
public static final String PRO_CLIENT_SUFFIX = "clientSuffix"; // client 结尾
public static final String PRO_EXAMPLE_SUFFIX = "exampleSuffix"; // example 结尾
public static final String PRO_MODEL_SUFFIX = "modelSuffix"; // model 结尾
private String tableSearchString;
private String tableReplaceString;
private boolean tableReplaceDisable;
private String columnSearchString;
private String columnReplaceString;
private boolean columnReplaceDisable;
private String clientSuffix; // client 结尾
private String exampleSuffix; // example 结尾
private String modelSuffix; // model 结尾
/**
* {@inheritDoc}
* @param warnings
* @return
*/
@Override
public boolean validate(List<String> warnings) {
Properties properties = this.getProperties();
this.tableSearchString = properties.getProperty(PRO_TABLE_SEARCH_STRING);
this.tableReplaceString = properties.getProperty(PRO_TABLE_REPLACE_STRING);
this.columnSearchString = properties.getProperty(PRO_COLUMN_SEARCH_STRING);
this.columnReplaceString = properties.getProperty(PRO_COLUMN_REPLACE_STRING); // 和官方行为保持一致
this.exampleSuffix = properties.getProperty(PRO_EXAMPLE_SUFFIX);
this.clientSuffix = properties.getProperty(PRO_CLIENT_SUFFIX);
this.modelSuffix = properties.getProperty(PRO_MODEL_SUFFIX);
return super.validate(warnings);
}
/**
* 表配置
* @param introspectedTable
*/
@Override
public void tableConfiguration(IntrospectedTable introspectedTable) {
try {
TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration();
FullyQualifiedTable fullyQualifiedTable = introspectedTable.getFullyQualifiedTable();
String tableReplaceDisable = tableConfiguration.getProperty(PRO_TABLE_REPLACE_DISABLE);
this.tableReplaceDisable = tableReplaceDisable == null ? false : StringUtility.isTrue(tableReplaceDisable);
String columnReplaceDisable = tableConfiguration.getProperty(PRO_COLUMN_REPLACE_DISABLE);
this.columnReplaceDisable = columnReplaceDisable == null ? false : StringUtility.isTrue(columnReplaceDisable);
String javaClientInterfacePackage = (String) BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaClientInterfacePackage");
String sqlMapPackage = (String) BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateSqlMapPackage");
String javaModelPackage = (String) BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaModelPackage");
// --------------------- table 重命名 ----------------------------
if (tableConfiguration.getDomainObjectRenamingRule() == null
&& this.tableSearchString != null && !this.tableReplaceDisable) {
DomainObjectRenamingRule rule = new DomainObjectRenamingRule();
rule.setSearchString(this.tableSearchString);
rule.setReplaceString(this.tableReplaceString);
tableConfiguration.setDomainObjectRenamingRule(rule);
BeanUtils.setProperty(introspectedTable.getFullyQualifiedTable(), "domainObjectRenamingRule", rule);
// 重新初始化一下属性
BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaClientAttributes");
BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateModelAttributes");
BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateXmlAttributes");
}
// TODO 官方bug临时修复
if (tableConfiguration.getDomainObjectRenamingRule() != null) {
String domainObjectName = fullyQualifiedTable.getDomainObjectName();
// 首字母大写
BeanUtils.setProperty(fullyQualifiedTable, "domainObjectName", getCamelCaseString(domainObjectName, true));
// 重新初始化一下属性
BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaClientAttributes");
BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateModelAttributes");
BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateXmlAttributes");
}
// --------------------- column 重命名 ---------------------------
if (tableConfiguration.getColumnRenamingRule() == null
&& this.columnSearchString != null && !this.columnReplaceDisable) {
ColumnRenamingRule rule = new ColumnRenamingRule();
rule.setSearchString(this.columnSearchString);
rule.setReplaceString(this.columnReplaceString);
tableConfiguration.setColumnRenamingRule(rule);
// introspectedTable 使用到的所有column过滤并替换
this.renameColumns(introspectedTable.getAllColumns(), rule, tableConfiguration);
}
// ---------------------- 后缀修正 -------------------------------
// 1. client
if (this.clientSuffix != null) {
// mapper
StringBuilder sb = new StringBuilder();
sb.append(javaClientInterfacePackage);
sb.append('.');
if (stringHasValue(tableConfiguration.getMapperName())) {
sb.append(tableConfiguration.getMapperName());
} else {
if (stringHasValue(fullyQualifiedTable.getDomainObjectSubPackage())) {
sb.append(fullyQualifiedTable.getDomainObjectSubPackage());
sb.append('.');
}
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append(this.clientSuffix);
}
introspectedTable.setMyBatis3JavaMapperType(sb.toString());
// xml mapper namespace
sb.setLength(0);
sb.append(sqlMapPackage);
sb.append('.');
if (stringHasValue(tableConfiguration.getMapperName())) {
sb.append(tableConfiguration.getMapperName());
} else {
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append(this.clientSuffix);
}
introspectedTable.setMyBatis3FallbackSqlMapNamespace(sb.toString());
// xml file
sb.setLength(0);
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append(this.clientSuffix);
sb.append(".xml");
introspectedTable.setMyBatis3XmlMapperFileName(sb.toString());
}
// 2. example
if (this.exampleSuffix != null) {
StringBuilder sb = new StringBuilder();
sb.append(javaModelPackage);
sb.append('.');
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append(this.exampleSuffix);
introspectedTable.setExampleType(sb.toString());
}
// 3. model
if (this.modelSuffix != null) {
StringBuilder sb = new StringBuilder();
sb.append(javaModelPackage);
sb.append('.');
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append("Key");
sb.append(this.modelSuffix);
introspectedTable.setPrimaryKeyType(sb.toString());
sb.setLength(0);
sb.append(javaModelPackage);
sb.append('.');
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append(this.modelSuffix);
introspectedTable.setBaseRecordType(sb.toString());
sb.setLength(0);
sb.append(javaModelPackage);
sb.append('.');
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append("WithBLOBs");
sb.append(this.modelSuffix);
introspectedTable.setRecordWithBLOBsType(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* column rename
* @param columns
* @param rule
* @param tc
*/
private void renameColumns(List<IntrospectedColumn> columns, ColumnRenamingRule rule, TableConfiguration tc) {
Pattern pattern = Pattern.compile(rule.getSearchString());
String replaceString = rule.getReplaceString();
replaceString = replaceString == null ? "" : replaceString;
for (IntrospectedColumn introspectedColumn : columns) {
String calculatedColumnName;
if (pattern == null) {
calculatedColumnName = introspectedColumn.getActualColumnName();
} else {
Matcher matcher = pattern.matcher(introspectedColumn.getActualColumnName());
calculatedColumnName = matcher.replaceAll(replaceString);
}
if (isTrue(tc.getProperty(PropertyRegistry.TABLE_USE_ACTUAL_COLUMN_NAMES))) {
introspectedColumn.setJavaProperty(getValidPropertyName(calculatedColumnName));
} else if (isTrue(tc.getProperty(PropertyRegistry.TABLE_USE_COMPOUND_PROPERTY_NAMES))) {
StringBuilder sb = new StringBuilder();
sb.append(calculatedColumnName);
sb.append('_');
sb.append(getCamelCaseString(introspectedColumn.getRemarks(), true));
introspectedColumn.setJavaProperty(getValidPropertyName(sb.toString()));
} else {
introspectedColumn.setJavaProperty(getCamelCaseString(calculatedColumnName, false));
}
}
}
}
@@ -33,6 +33,7 @@ import java.util.regex.Pattern;
* @time:2017/6/6 15:18
* ---------------------------------------------------------------------------
*/
@Deprecated
public class TableRenamePlugin extends BasePlugin {
public static final String PRO_SEARCH_STRING = "searchString"; // 查找 property
public static final String PRO_REPLACE_STRING = "replaceString"; // 替换 property
@@ -94,6 +95,7 @@ public class TableRenamePlugin extends BasePlugin {
logger.error("itfsw:插件" + this.getClass().getTypeName() + "使用searchString、replaceString替换时异常!", e);
}
}
super.initialized(introspectedTable);
}
/**
@@ -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") + "实现方法。");
}
}
@@ -19,7 +19,9 @@ package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.CommentPlugin;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.TemplateCommentGenerator;
import com.itfsw.mybatis.generator.plugins.utils.hook.HookAggregator;
import com.itfsw.mybatis.generator.plugins.utils.hook.ITableConfigurationHook;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.PluginConfiguration;
@@ -97,4 +99,14 @@ public class BasePlugin extends PluginAdapter {
return true;
}
/**
* {@inheritDoc}
* @param introspectedTable
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
PluginTools.getHook(ITableConfigurationHook.class).tableConfiguration(introspectedTable);
}
}
@@ -58,14 +58,15 @@ public class BeanUtils {
/**
* 执行无参方法
* @param bean
* @param clazz
* @param name
* @return
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static Object invoke(final Object bean, final String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = bean.getClass().getDeclaredMethod(name);
public static Object invoke(final Object bean, Class clazz, final String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = clazz.getDeclaredMethod(name);
method.setAccessible(true);
return method.invoke(bean);
}
@@ -43,7 +43,7 @@ import java.util.List;
* @time:2018/4/27 11:33
* ---------------------------------------------------------------------------
*/
public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHook, IIncrementsPluginHook, IOptimisticLockerPluginHook, ISelectOneByExamplePluginHook {
public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHook, IIncrementsPluginHook, IOptimisticLockerPluginHook, ISelectOneByExamplePluginHook, ITableConfigurationHook {
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class); // 日志
private final static HookAggregator instance = new HookAggregator();
private Context context;
@@ -250,4 +250,13 @@ public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHoo
}
return true;
}
// ============================================= ITableConfigurationHook ==============================================
@Override
public void tableConfiguration(IntrospectedTable introspectedTable) {
if (!this.getPlugins(ITableConfigurationHook.class).isEmpty()) {
this.getPlugins(ITableConfigurationHook.class).get(0).tableConfiguration(introspectedTable);
}
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2018.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins.utils.hook;
import org.mybatis.generator.api.IntrospectedTable;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/5/21 11:24
* ---------------------------------------------------------------------------
*/
public interface ITableConfigurationHook {
/**
* 表配置
* @param introspectedTable
*/
void tableConfiguration(IntrospectedTable introspectedTable);
}
@@ -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);
}
});
}
@@ -0,0 +1,278 @@
/*
* Copyright (c) 2018.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.*;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/5/22 13:22
* ---------------------------------------------------------------------------
*/
public class TableRenameConfigurationPluginTest {
@BeforeClass
public static void init() throws Exception {
DBHelper.createDB("scripts/TableRenameConfigurationPlugin/init.sql");
}
/**
* 测试domainObjectRenamingRule
*/
@Test
public void testDomainObjectRenamingRule() throws Exception {
// 规则 ^T 替换成空,也就是去掉前缀
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableRenameConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule-relacePrefix.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()){
String name = file.getCompilationUnit().getType().getShortName();
if (!name.matches("B.*")){
Assert.assertTrue(false);
}
}
// 规则 ^T 替换成 Test
tool = MyBatisGeneratorTool.create("scripts/TableRenameConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule.xml");
myBatisGenerator = tool.generate();
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()){
String name = file.getCompilationUnit().getType().getShortName();
if (!(name.matches("Testb.*") || name.matches("TbBlobs.*"))){
Assert.assertTrue(false);
}
}
// 执行一条语句确认其可用
tool.generate(() -> DBHelper.resetDB("scripts/TableRenameConfigurationPlugin/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 + ".TestbMapper")));
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TestbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andIdLessThan", 4L);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbExample.getObject());
Assert.assertEquals(sql, "select id, field1, inc_f1, inc_f2, inc_f3 from tb WHERE ( id < '4' )");
// 执行
List list = (List) tbMapper.invoke("selectByExample", tbExample.getObject());
Assert.assertEquals(list.size(), 3);
}
});
}
/**
* 测试columnRenamingRule
*/
@Test
public void testColumnRenamingRule() throws Exception {
// 规则 ^T 替换成 Test
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableRenameConfigurationPlugin/mybatis-generator-with-columnRenamingRule.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()){
if (file.getFileName().equals("Tb.java")){
int count = 0;
for (Field field : ((TopLevelClass)(file.getCompilationUnit())).getFields()){
if (field.getName().startsWith("increment")){
count++;
}
}
Assert.assertEquals(count, 3);
}
if (file.getFileName().equals("TbBlobs.java")){
int count = 0;
for (Field field : ((TopLevelClass)(file.getCompilationUnit())).getFields()){
if (field.getName().startsWith("increment")){
count++;
}
}
Assert.assertEquals(count, 0);
}
}
// 执行一条语句确认其可用
tool.generate(() -> DBHelper.resetDB("scripts/TableRenameConfigurationPlugin/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")));
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andIdEqualTo", 4L);
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 4L);
tb.set("field1", "ts1");
tb.set("incrementF1", 5L);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExample", tb.getObject(), tbExample.getObject());
Assert.assertEquals(sql, "update tb set id = 4, field1 = 'ts1', inc_f1 = 5, inc_f2 = null, inc_f3 = null WHERE ( id = '4' )");
// 执行
int count = (int) tbMapper.invoke("updateByExample", tb.getObject(), tbExample.getObject());
Assert.assertEquals(count, 1);
// 执行结果查询
List list = (List) tbMapper.invoke("selectByExample", tbExample.getObject());
ObjectUtil result = new ObjectUtil(list.get(0));
Assert.assertEquals(result.get("id"), 4L);
Assert.assertEquals(result.get("field1"), "ts1");
Assert.assertEquals(result.get("incrementF1"), 5L);
}
});
}
/**
* 测试clientSuffix
*/
@Test
public void testClientSuffix() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableRenameConfigurationPlugin/mybatis-generator-with-clientSuffix.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
boolean find = false;
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
String name = file.getCompilationUnit().getType().getShortName();
if (name.equals("TbDao")){
find = true;
}
}
Assert.assertTrue(find);
find = false;
for (GeneratedXmlFile file : myBatisGenerator.getGeneratedXmlFiles()) {
String name = file.getFileName();
if (name.equals("TbDao.xml")){
find = true;
}
}
Assert.assertTrue(find);
// 执行一条语句确认其可用
tool.generate(() -> DBHelper.resetDB("scripts/TableRenameConfigurationPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbDao = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbDao")));
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andIdLessThan", 4L);
// sql
String sql = SqlHelper.getFormatMapperSql(tbDao.getObject(), "selectByExample", tbExample.getObject());
Assert.assertEquals(sql, "select id, field1, inc_f1, inc_f2, inc_f3 from tb WHERE ( id < '4' )");
// 执行
List list = (List) tbDao.invoke("selectByExample", tbExample.getObject());
Assert.assertEquals(list.size(), 3);
}
});
}
/**
* 测试exampleSuffix
*/
@Test
public void testExampleSuffix() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableRenameConfigurationPlugin/mybatis-generator-with-exampleSuffix.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
boolean find = false;
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
String name = file.getCompilationUnit().getType().getShortName();
if (name.equals("TbQuery")){
find = true;
}
}
Assert.assertTrue(find);
// 执行一条语句确认其可用
tool.generate(() -> DBHelper.resetDB("scripts/TableRenameConfigurationPlugin/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")));
ObjectUtil tbQuery = new ObjectUtil(loader, packagz + ".TbQuery");
ObjectUtil criteria = new ObjectUtil(tbQuery.invoke("createCriteria"));
criteria.invoke("andIdLessThan", 4L);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbQuery.getObject());
Assert.assertEquals(sql, "select id, field1, inc_f1, inc_f2, inc_f3 from tb WHERE ( id < '4' )");
// 执行
List list = (List) tbMapper.invoke("selectByExample", tbQuery.getObject());
Assert.assertEquals(list.size(), 3);
}
});
}
/**
* 测试modelSuffix
*/
@Test
public void testModelSuffix() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableRenameConfigurationPlugin/mybatis-generator-with-modelSuffix.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
boolean find = false;
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
String name = file.getCompilationUnit().getType().getShortName();
if (name.equals("TbEntity")){
find = true;
}
}
Assert.assertTrue(find);
// 执行一条语句确认其可用
tool.generate(() -> DBHelper.resetDB("scripts/TableRenameConfigurationPlugin/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")));
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andIdEqualTo", 4L);
ObjectUtil tb = new ObjectUtil(loader, packagz + ".TbEntity");
tb.set("id", 4L);
tb.set("field1", "ts1");
tb.set("incF1", 5L);
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExample", tb.getObject(), tbExample.getObject());
Assert.assertEquals(sql, "update tb set id = 4, field1 = 'ts1', inc_f1 = 5, inc_f2 = null, inc_f3 = null WHERE ( id = '4' )");
// 执行
int count = (int) tbMapper.invoke("updateByExample", tb.getObject(), tbExample.getObject());
Assert.assertEquals(count, 1);
// 执行结果查询
List list = (List) tbMapper.invoke("selectByExample", tbExample.getObject());
ObjectUtil result = new ObjectUtil(list.get(0));
Assert.assertEquals(result.get("id"), 4L);
Assert.assertEquals(result.get("field1"), "ts1");
Assert.assertEquals(result.get("incF1"), 5L);
}
});
}
}
@@ -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
@@ -0,0 +1,120 @@
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50617
Source Host : localhost:3306
Source Database : mybatis-generator-plugin
Target Server Type : MYSQL
Target Server Version : 50617
File Encoding : 65001
Date: 2017-07-05 17:21:41
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM 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');
-- ----------------------------
-- Table structure for tb_blobs
-- ----------------------------
DROP TABLE IF EXISTS `tb_blobs`;
CREATE TABLE `tb_blobs` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL,
`field2` longtext COMMENT '注释2',
`field3` longtext,
`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=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
-- ----------------------------
INSERT INTO `tb_blobs` VALUES ('1', 'fd1', null, null, '1', '2', '3');
INSERT INTO `tb_blobs` VALUES ('2', null, 'fd2', null, '3', '2', '1');
INSERT INTO `tb_blobs` VALUES ('3', null, null, 'fd3', '1', '1', '1');
INSERT INTO `tb_blobs` VALUES ('4', 'fd4', 'fd5', 'fd6', '0', '0', '0');
-- ----------------------------
-- Table structure for tb_keys
-- ----------------------------
DROP TABLE IF EXISTS `tb_keys`;
CREATE TABLE `tb_keys` (
`key1` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`key2` varchar(255) NOT NULL,
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
`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 (`key1`,`key2`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
-- ----------------------------
INSERT INTO `tb_keys` VALUES ('1', 'k1', 'fd1', null, '1', '2', '3');
INSERT INTO `tb_keys` VALUES ('2', 'k2', null, '2', '3', '2', '1');
INSERT INTO `tb_keys` VALUES ('3', 'k3', null, null, '1', '1', '1');
-- ----------------------------
-- Table structure for tb_single_blob
-- ----------------------------
DROP TABLE IF EXISTS `tb_single_blob`;
CREATE TABLE `tb_single_blob` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` longtext COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
`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=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
-- ----------------------------
INSERT INTO `tb_single_blob` VALUES ('1', 'fd1', '0', '1', '2', '3');
INSERT INTO `tb_single_blob` VALUES ('2', null, null, '3', '2', '1');
INSERT INTO `tb_single_blob` VALUES ('3', null, null, '1', '1', '1');
-- ----------------------------
-- Table structure for tb_key_word
-- ----------------------------
DROP TABLE IF EXISTS `tb_key_word`;
CREATE TABLE `tb_key_word` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field2` int(11) DEFAULT NULL,
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`update` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_key_word
-- ----------------------------
INSERT INTO `tb_key_word` VALUES ('1', '0', '0', '1');
@@ -0,0 +1,56 @@
<?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.TableRenameConfigurationPlugin">
<property name="clientSuffix" value="Dao"/>
</plugin>
<!--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"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,60 @@
<?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.TableRenameConfigurationPlugin">
<property name="columnRenamingRule.searchString" value="^inc_"/>
<property name="columnRenamingRule.replaceString" value="Increment_"/>
</plugin>
<!--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_blobs">
<property name="columnRenamingRule.disable" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
@@ -0,0 +1,56 @@
<?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.TableRenameConfigurationPlugin">
<property name="domainObjectRenamingRule.searchString" value="^T"/>
<property name="domainObjectRenamingRule.replaceString" value=""/>
</plugin>
<!--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>
</context>
</generatorConfiguration>
@@ -0,0 +1,60 @@
<?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.TableRenameConfigurationPlugin">
<property name="domainObjectRenamingRule.searchString" value="^T"/>
<property name="domainObjectRenamingRule.replaceString" value="Test"/>
</plugin>
<!--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_blobs">
<property name="domainObjectRenamingRule.disable" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
@@ -0,0 +1,56 @@
<?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.TableRenameConfigurationPlugin">
<property name="exampleSuffix" value="Query"/>
</plugin>
<!--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"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,56 @@
<?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.TableRenameConfigurationPlugin">
<property name="modelSuffix" value="Entity"/>
</plugin>
<!--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"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,65 @@
<?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.TableRenameConfigurationPlugin">
<property name="searchString" value="^"/>
<property name="replaceString" value="DB1"/>
<property name="suffixForMapper" value="Dao"/>
</plugin>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<property name="incrementsColumns" value="inc_f1"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys">
<property name="incrementsColumns" value=" inc_f1, inc_f2, inc_f3 "/>
</table>
<table tableName="tb_blobs">
<property name="incrementsColumns" value="inc_f1,inc_f3"/>
</table>
</context>
</generatorConfiguration>
@@ -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>