Compare commits

...
19 Commits
Author SHA1 Message Date
hewei 7df2d4e27f [maven-release-plugin] prepare release V1.2.17 2019-01-14 17:10:53 +08:00
hewei 42f6a2ce28 fix#69:当OptimisticLockerPlugin配置在SelectiveEnhancedPlugin之后时,代码没有检查是否已经附加了selective参数 2019-01-14 17:07:27 +08:00
hewei 2a75e9cf53 V1.2.16 2019-01-10 10:59:22 +08:00
hewei fab929d352 [maven-release-plugin] prepare for next development iteration 2019-01-10 10:45:37 +08:00
hewei 39568d91af [maven-release-plugin] prepare release V1.2.16 2019-01-10 10:45:09 +08:00
hewei b4b645964f fix#68:使用 gradle 编译报警告 2019-01-10 10:43:07 +08:00
hewei 5c5c7765b8 增加CommentPlugin的测试用例 2019-01-10 10:40:27 +08:00
hewei f3be4ea6dc fix#68:使用 gradle 编译报警告 2019-01-10 10:38:01 +08:00
hewei 37161f24b3 fix: 逻辑删除插件常量应该放在类开头 2018-12-20 17:26:19 +08:00
hewei 1d1c7b10b9 [maven-release-plugin] prepare for next development iteration 2018-12-20 16:45:34 +08:00
hewei f36b3190f2 [maven-release-plugin] prepare release V1.2.15 2018-12-20 16:45:18 +08:00
hewei a6bd2dcf0f 兼容老版本配置 2018-12-20 16:42:47 +08:00
hewei 1de9e889c1 逻辑删除插件增加基于注解的枚举实现 2018-12-20 16:03:14 +08:00
hewei 095470fc2c 逻辑删除插件增加基于注解的枚举实现 2018-12-20 15:20:48 +08:00
hewei 236b388545 增加测试用例 2018-12-20 13:47:27 +08:00
hewei 01f84c52f3 扩充EnumTypeStatusPlugin支持的数据类型范围 2018-12-19 18:17:03 +08:00
hewei 1c1a8acc7b V1.2.14 2018-12-19 15:46:21 +08:00
hewei c4e29152b6 V1.2.14 2018-12-19 15:22:21 +08:00
hewei bc9ebf27b0 [maven-release-plugin] prepare for next development iteration 2018-12-19 11:01:10 +08:00
22 changed files with 1063 additions and 307 deletions
+190 -7
View File
@@ -26,6 +26,7 @@
* [表重命名配置插件(TableRenameConfigurationPlugin)](#18-表重命名配置插件)
* [Lombok插件(LombokPlugin)](#19-Lombok插件)
* [数据ModelCloneable插件(ModelCloneablePlugin)](#20-数据ModelCloneable插件)
* [状态枚举生成插件(EnumTypeStatusPlugin)](#21-状态枚举生成插件)
---------------------------------------
Maven引用:
@@ -33,7 +34,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.12</version>
<version>1.2.16</version>
</dependency>
```
---------------------------------------
@@ -88,7 +89,7 @@ targetCompatibility = 1.8
def mybatisGeneratorCore = 'org.mybatis.generator:mybatis-generator-core:1.3.7'
def itfswMybatisGeneratorPlugin = 'com.itfsw:mybatis-generator-plugin:1.2.12'
def itfswMybatisGeneratorPlugin = 'com.itfsw:mybatis-generator-plugin:1.2.16'
mybatisGenerator {
verbose = false
@@ -280,16 +281,19 @@ public class Test {
```
### 4. Example 增强插件(example,andIf,orderBy)
* Criteria的快速返回example()方法。
* Criteria链式调用增强,以前如果有按条件增加的查询语句会打乱链式查询构建,现在有了andIf(boolean ifAdd, CriteriaAdd add)方法可一直使用链式调用下去。
* Example增强了setOrderByClause方法,新增orderBy(String orderByClause)方法直接返回example,增强链式调用,可以一路.下去了。
* 继续增强orderBy(String orderByClause)方法,增加orderBy(String ... orderByClauses)方法,配合数据Model属性对应Column获取插件(ModelColumnPlugin)使用效果更佳。
* ~~Criteria链式调用增强,以前如果有按条件增加的查询语句会打乱链式查询构建,现在有了andIf(boolean ifAdd, CriteriaAdd add)方法可一直使用链式调用下去。~~
* Example增强了setOrderByClause方法,新增orderBy(String orderByClause)、orderBy(String ... orderByClauses)方法直接返回example,增强链式调用,配合数据Model属性对应Column获取插件(ModelColumnPlugin)使用效果更佳。
* 增加基于column的操作,当配置了[数据Model属性对应Column获取插件(ModelColumnPlugin)](#8-数据model属性对应column获取插件)插件时,提供column之间的比对操作。
* 增加createCriteria静态方法newAndCreateCriteria简写example的创建。
* 增加when方法(Example和Criteria都有),方便根据不同条件附加对应操作。
插件:
```xml
<!-- Example Criteria 增强插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin">
<!-- 是否支持已经过时的andIf方法(推荐使用when代替),默认支持 -->
<property name="enableAndIf" value="true"/>
</plugin>
```
使用:
```java
@@ -305,7 +309,7 @@ public class Test {
.example()
);
// -----------------------------------andIf-----------------------------------
// ----------------- andIf (@Deprecated 尽量使用when代替) ---------------------
// Criteria增强了链式调用,现在一些按条件增加的查询条件不会打乱链式调用了
// old
TbExample oldEx = new TbExample();
@@ -342,6 +346,25 @@ public class Test {
.example()
);
// -----------------------------------when-----------------------------------
this.tbMapper.selectByExample(
TbExample.newAndCreateCriteria()
// 如果随机数大于1,附加Field3查询条件
.when(Math.random() > 1, new TbExample.ICriteriaWhen() {
@Override
public void criteria(TbExample.Criteria criteria) {
criteria.andField3EqualTo(2);
}
})
// 当然最简洁的写法是采用java8的Lambda表达式,当然你的项目是Java8+
.when(Math.random() > 1, criteria -> criteria.andField3EqualTo(2))
// 也支持 if else 这种写法
.when(Math.random() > 1, criteria -> criteria.andField3EqualTo(2), criteria -> criteria.andField3EqualTo(3))
.example()
// example上也支持 when 方法
.when(true, example -> example.orderBy("field1 DESC"))
);
// -----------------------------------orderBy-----------------------------------
// old
TbExample ex = new TbExample();
@@ -449,6 +472,9 @@ public class Test {
- 查询构造工具中增加逻辑删除条件andLogicalDeleted(boolean);
- 数据Model增加逻辑删除条件andLogicalDeleted(boolean);
- 增加逻辑删除常量IS_DELETED(已删除 默认值)、NOT_DELETED(未删除 默认值)([[issues#11]](https://github.com/itfsw/mybatis-generator-plugin/issues/11));
- 增加逻辑删除枚举,通过注解覆盖逻辑删除配置,具体使用参照[状态枚举生成插件(EnumTypeStatusPlugin)](#21-状态枚举生成插件)。
>warning: 使用注解生成逻辑删除枚举时,枚举数量必须大于等于2,且第一个代表未删除,第二个代表删除。同时不必配置enumColumns选项,逻辑删除插件使用logicalDeleteColumn覆盖该配置。
插件:
```xml
@@ -462,6 +488,9 @@ public class Test {
<property name="logicalDeleteValue" value="9"/>
<!-- 逻辑删除-未删除值 -->
<property name="logicalUnDeleteValue" value="0"/>
<!-- 是否生成逻辑删除常量(只有开启时 logicalDeleteConstName、logicalUnDeleteConstName 才生效) -->
<property name="enableLogicalDeleteConst" value="true"/>
<!-- 逻辑删除常量名称,不配置默认为 IS_DELETED -->
<property name="logicalDeleteConstName" value="IS_DELETED"/>
<!-- 逻辑删除常量(未删除)名称,不配置默认为 NOT_DELETED -->
@@ -513,9 +542,58 @@ public class Test {
// 5. selectByPrimaryKeyWithLogicalDelete V1.0.18 版本增加
// 因为之前觉得既然拿到了主键这种查询没有必要,但是实际使用中可能存在根据主键判断是否逻辑删除的情况,这种场景还是有用的
this.tbMapper.selectByPrimaryKeyWithLogicalDelete(1, true);
// 6. 使用逻辑删除枚举
Tb tb = Tb.builder()
.delFlag(Tb.DelFlag.IS_DELETED) // 删除
.delFlag(Tb.DelFlag.NOT_DELETED) // 未删除
.build()
.andLogicalDeleted(true); // 也可以在这里使用true|false设置逻辑删除
}
}
```
通过注解覆盖逻辑删除配置
```sql
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`del_flag` smallint(3) COMMENT '注释[enable(1):第一项必须是代表未删除, disable(0):第二项必须是代表已删除, other(2):当然还可以附加其他状态]',
PRIMARY KEY (`id`)
);
```
```java
/**
* 生成的Tb会根据注释覆盖逻辑删除配置
*/
public class Tb {
public static final Short ENABLE = DelFlag.ENABLE.value();
public static final Short DISABLE = DelFlag.DISABLE.value();
public enum DelFlag {
ENABLE(new Short("1"), "第一项必须是代表未删除"),
DISABLE(new Short("0"), "第二项必须是代表已删除"),
OTHER(new Short("2"), "当然还可以附加其他状态");
private final Short value;
private final String name;
DelFlag(Short value, String name) {
this.value = value;
this.name = name;
}
public Short getValue() {
return this.value;
}
public Short value() {
return this.value;
}
public String getName() {
return this.name;
}
}
}
```
### 8. 数据Model属性对应Column获取插件
项目中我们有时需要获取数据Model对应数据库字段的名称,一般直接根据数据Model的属性就可以猜出数据库对应column的名字,可是有的时候当column使用了columnOverride或者columnRenamingRule时就需要去看数据库设计了,所以提供了这个插件获取model对应的数据库Column。
* 配合Example Criteria 增强插件(ExampleEnhancedPlugin)使用,这个插件还提供了asc()和desc()方法配合Example的orderBy方法效果更佳。
@@ -1393,4 +1471,109 @@ public class Test {
<!-- 数据ModelCloneable插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelCloneablePlugin"/>
</xml>
```
### 21. 状态枚举生成插件
数据库中经常会定义一些状态字段,该工具可根据约定的注释格式生成对应的枚举类,方便使用。
```xml
<xml>
<!-- 状态枚举生成插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.EnumTypeStatusPlugin">
<!-- 这里可以定义全局需要检查生成枚举类的列名 -->
<property name="enumColumns" value="type, status"/>
</plugin>
<table tableName="tb">
<!-- 也可以为单独某个table增加配置 -->
<property name="enumColumns" value="user_type"/>
</table>
</xml>
```
>warning: 约定的注释检查规则的正则表达式如下
```java
public class EnumTypeStatusPlugin {
public final static String REMARKS_PATTERN = ".*\\s*\\[\\s*(\\w+\\s*\\(\\s*[\\u4e00-\\u9fa5_a-zA-Z0-9]+\\s*\\)\\s*:\\s*[\\u4e00-\\u9fa5_a-zA-Z0-9]+\\s*\\,?\\s*)+\\s*\\]\\s*.*";
}
```
使用
```sql
CREATE TABLE `tb` (
`type` smallint(3) COMMENT '注释[success(0):成功, fail(1):失败]',
`status` bigint(3) COMMENT '换行的注释
[
login_success(0):登录成功,
login_fail(1):登录失败
]',
`user_type` varchar(20) COMMENT '具体注释的写法是比较宽泛的,只要匹配上面正则就行
[ success ( 我是具体值 ) : 我是值的描述_我可以是中英文数字和下划线_xxx_123, fail_xx_3
(1 ) : 失败] 后面也可以跟注释'
);
```
```java
public class Tb {
public enum Type {
SUCCESS((short)0, "成功"),
FAIL((short)1, "失败");
private final Short value;
private final String name;
Type(Short value, String name) {
this.value = value;
this.name = name;
}
public Short getValue() {
return this.value;
}
public Short value() {
return this.value;
}
public String getName() {
return this.name;
}
}
public enum Status {
LOGIN_SUCCESS(0L, "登录成功"),
LOGIN_FAIL(1L, "登录失败");
private final Long value;
private final String name;
Status(Long value, String name) {
this.value = value;
this.name = name;
}
public Long getValue() {
return this.value;
}
public Long value() {
return this.value;
}
public String getName() {
return this.name;
}
}
public enum UserType {
SUCCESS("我是具体值", "我是值的描述_我可以是中英文数字和下划线_xxx_123"),
FAIL_XX_3("1", "失败");
private final String value;
private final String name;
UserType(String value, String name) {
this.value = value;
this.name = name;
}
public String getValue() {
return this.value;
}
public String value() {
return this.value;
}
public String getName() {
return this.name;
}
}
}
```
+12 -4
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.14</version>
<version>1.2.17</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -97,16 +97,24 @@
<version>[1.18.2,)</version>
<scope>test</scope>
</dependency>
<!-- lombok dependency -->
<!-- lombok 的测试用例依赖tools.jar, 但直接使用以下方式配置会导致gradle报错
解决办法:把tools.jar 安装进本地仓库!!
mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dpackaging=jar -Dversion=1.8 -Dfile=tools.jar
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8</version>
<scope>system</scope>
<optional>true</optional>
<!-- jdk path -->
<systemPath>${env.JAVA_HOME}/lib/tools.jar</systemPath>
</dependency>
-->
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.8</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++profiles++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -234,7 +242,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.14</tag>
<tag>V1.2.17</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -20,11 +20,13 @@ import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.FormatTools;
import com.itfsw.mybatis.generator.plugins.utils.IntrospectedTableTools;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.StringUtility;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -48,7 +50,7 @@ public class EnumTypeStatusPlugin extends BasePlugin {
public final static String REMARKS_PATTERN = ".*\\s*\\[\\s*(\\w+\\s*\\(\\s*[\\u4e00-\\u9fa5_a-zA-Z0-9]+\\s*\\)\\s*:\\s*[\\u4e00-\\u9fa5_a-zA-Z0-9]+\\s*\\,?\\s*)+\\s*\\]\\s*.*";
public final static String NEED_PATTERN = "\\[\\s*((\\w+\\s*\\(\\s*[\\u4e00-\\u9fa5_a-zA-Z0-9]+\\s*\\)\\s*:\\s*[\\u4e00-\\u9fa5_a-zA-Z0-9]+\\s*\\,?\\s*)+)\\s*\\]";
public final static String ITEM_PATTERN = "(\\w+)\\s*\\(\\s*([\\u4e00-\\u9fa5_a-zA-Z0-9]+)\\s*\\)\\s*:\\s*([\\u4e00-\\u9fa5_a-zA-Z0-9]+)";
private Map<IntrospectedColumn, List<EnumItemInfo>> enumColumns;
private Map<String, EnumInfo> enumColumns;
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
@@ -75,39 +77,17 @@ public class EnumTypeStatusPlugin extends BasePlugin {
for (String enumColumnsStr : enumColumnsStrs) {
IntrospectedColumn column = IntrospectedTableTools.safeGetColumn(introspectedTable, enumColumnsStr);
if (column != null) {
String remarks = column.getRemarks();
String javaType = column.getFullyQualifiedJavaType().getFullyQualifiedName();
if (!StringUtility.stringHasValue(remarks) || !remarks.matches(REMARKS_PATTERN)) {
try {
EnumInfo enumInfo = new EnumInfo(column);
// 解析注释
enumInfo.parseRemarks(column.getRemarks());
if (enumInfo.hasItems()) {
this.enumColumns.put(column.getJavaProperty(), enumInfo);
}
} catch (EnumInfo.CannotParseException e) {
warnings.add("itfsw:插件" + EnumTypeStatusPlugin.class.getTypeName() + "没有找到column为" + enumColumnsStr.trim() + "对应格式的注释的字段!");
} else if (!(Short.class.getTypeName().equals(javaType)
|| Integer.class.getTypeName().equals(javaType)
|| Long.class.getTypeName().equals(javaType)
|| String.class.getTypeName().equals(javaType))) {
warnings.add("itfsw:插件" + EnumTypeStatusPlugin.class.getTypeName() + "找到column为" + enumColumnsStr.trim() + "对应Java类型不是Short、Integer、Long、String!");
} else {
// 提取信息
Pattern pattern = Pattern.compile(NEED_PATTERN);
Matcher matcher = pattern.matcher(remarks);
List<EnumItemInfo> itemInfos = new ArrayList<>();
if (matcher.find() && matcher.groupCount() == 2) {
String enumInfoStr = matcher.group(1);
// 根据逗号切分
String[] enumInfoStrs = enumInfoStr.split(",");
// 提取每个节点信息
for (String enumInfo : enumInfoStrs) {
pattern = Pattern.compile(ITEM_PATTERN);
matcher = pattern.matcher(enumInfo.trim());
if (matcher.find() && matcher.groupCount() == 3) {
itemInfos.add(new EnumItemInfo(column, matcher.group(1), matcher.group(3), matcher.group(2)));
}
}
}
if (itemInfos.size() > 0) {
this.enumColumns.put(column, itemInfos);
}
} catch (EnumInfo.NotSupportTypeException e) {
warnings.add("itfsw:插件" + EnumTypeStatusPlugin.class.getTypeName() + "找到column为" + enumColumnsStr.trim() + "对应Java类型不在支持范围内!");
}
}
}
@@ -132,63 +112,13 @@ public class EnumTypeStatusPlugin extends BasePlugin {
* @param introspectedTable
*/
private void generateModelEnum(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
this.enumColumns.forEach((introspectedColumn, enumItemInfos) -> {
// 枚举跟随字段走
for (Field field : topLevelClass.getFields()) {
if (introspectedColumn.getJavaProperty().equals(field.getName())) {
String enumName = this.upperCaseFirst(field.getName());
InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(enumName));
commentGenerator.addEnumComment(innerEnum, introspectedTable);
innerEnum.setVisibility(JavaVisibility.PUBLIC);
innerEnum.setStatic(true);
// 生成枚举
for (EnumItemInfo item : enumItemInfos) {
innerEnum.addEnumConstant(item.getName() + "(" + item.getValue() + ", " + item.getComment() + ")");
}
// 生成属性和构造函数
Field fValue = new Field("value", field.getType());
fValue.setVisibility(JavaVisibility.PRIVATE);
fValue.setFinal(true);
commentGenerator.addFieldComment(fValue, introspectedTable);
innerEnum.addField(fValue);
Field fName = new Field("name", FullyQualifiedJavaType.getStringInstance());
fName.setVisibility(JavaVisibility.PRIVATE);
fName.setFinal(true);
commentGenerator.addFieldComment(fName, introspectedTable);
innerEnum.addField(fName);
Method mInc = new Method(enumName);
mInc.setConstructor(true);
mInc.addBodyLine("this.value = value;");
mInc.addBodyLine("this.name = name;");
mInc.addParameter(new Parameter(fValue.getType(), "value"));
mInc.addParameter(new Parameter(fName.getType(), "name"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mInc);
// 获取value的方法
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mValue);
Method mValue1 = JavaElementGeneratorTools.generateGetterMethod(fValue);
mValue1.setName("value");
commentGenerator.addGeneralMethodComment(mValue1, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mValue1);
// 获取name的方法
Method mName = JavaElementGeneratorTools.generateGetterMethod(fName);
commentGenerator.addGeneralMethodComment(mName, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mName);
topLevelClass.addInnerEnum(innerEnum);
}
// 枚举跟随字段走
for (Field field : topLevelClass.getFields()) {
if (this.enumColumns.get(field.getName()) != null) {
InnerEnum innerEnum = this.enumColumns.get(field.getName()).generateEnum(commentGenerator, introspectedTable);
topLevelClass.addInnerEnum(innerEnum);
}
});
}
}
/**
@@ -204,66 +134,197 @@ public class EnumTypeStatusPlugin extends BasePlugin {
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
/**
* 首字母大写
* @param s
* @return
*/
private String upperCaseFirst(String s) {
if (Character.isUpperCase(s.charAt(0))) {
return s;
} else {
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
private class EnumItemInfo {
public static class EnumInfo {
private List<EnumItemInfo> items = new ArrayList<>();
private IntrospectedColumn column;
private String name;
private String comment;
private String value;
public EnumItemInfo(IntrospectedColumn column, String name, String comment, String value) {
this.column = column;
this.name = name;
this.comment = comment;
this.value = value;
public EnumInfo(IntrospectedColumn column) throws NotSupportTypeException, CannotParseException {
String javaType = column.getFullyQualifiedJavaType().getFullyQualifiedName();
if (!(Short.class.getTypeName().equals(javaType)
|| Integer.class.getTypeName().equals(javaType)
|| Long.class.getTypeName().equals(javaType)
|| Boolean.class.getTypeName().equals(javaType)
|| Double.class.getTypeName().equals(javaType)
|| Float.class.getTypeName().equals(javaType)
|| BigDecimal.class.getTypeName().equals(javaType)
|| Byte.class.getTypeName().equals(javaType)
|| String.class.getTypeName().equals(javaType))) {
throw new NotSupportTypeException();
} else {
this.column = column;
}
}
/**
* Getter method for property <tt>comment</tt>.
* @return property value of comment
* @author hewei
* 添加Enum Item
* @param name
* @param comment
* @param value
* @return
*/
public void addItem(String name, String comment, String value) {
items.add(new EnumItemInfo(this.column, name, comment, value));
}
/**
* 判断是否有节点
* @return
*/
public String getComment() {
return "\"" + comment.trim() + "\"";
public boolean hasItems() {
return items.size() > 0;
}
/**
* Getter method for property <tt>name</tt>.
* @return property value of name
* @author hewei
* 解析注释
* @param remarks
*/
public String getName() {
return name.trim().toUpperCase();
public void parseRemarks(String remarks) throws CannotParseException {
if (!StringUtility.stringHasValue(remarks) || !remarks.matches(REMARKS_PATTERN)) {
throw new CannotParseException();
} else {
// 提取信息
Pattern pattern = Pattern.compile(NEED_PATTERN);
Matcher matcher = pattern.matcher(remarks);
if (matcher.find() && matcher.groupCount() == 2) {
String enumInfoStr = matcher.group(1);
// 根据逗号切分
String[] enumInfoStrs = enumInfoStr.split(",");
// 提取每个节点信息
for (String enumInfoItemStr : enumInfoStrs) {
pattern = Pattern.compile(ITEM_PATTERN);
matcher = pattern.matcher(enumInfoItemStr.trim());
if (matcher.find() && matcher.groupCount() == 3) {
this.addItem(matcher.group(1), matcher.group(3), matcher.group(2));
}
}
}
}
}
/**
* Getter method for property <tt>value</tt>.
* @return property value of value
* Getter method for property <tt>items</tt>.
* @return property value of items
* @author hewei
*/
public String getValue() {
String javaType = this.column.getFullyQualifiedJavaType().getFullyQualifiedName();
if (Short.class.getTypeName().equals(javaType)) {
return "(short)" + value;
} else if (Long.class.getTypeName().equals(javaType)) {
return value + "L";
} else if (String.class.getTypeName().equals(javaType)) {
return "\"" + value + "\"";
public List<EnumItemInfo> getItems() {
return items;
}
public class NotSupportTypeException extends Exception {
}
public class CannotParseException extends Exception {
}
public InnerEnum generateEnum(CommentGenerator commentGenerator, IntrospectedTable introspectedTable) {
String enumName = FormatTools.upFirstChar(column.getJavaProperty());
InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(enumName));
commentGenerator.addEnumComment(innerEnum, introspectedTable);
innerEnum.setVisibility(JavaVisibility.PUBLIC);
innerEnum.setStatic(true);
// 生成枚举
for (EnumItemInfo item : this.items) {
innerEnum.addEnumConstant(item.getName() + "(" + item.getValue() + ", " + item.getComment() + ")");
}
// 生成属性和构造函数
Field fValue = new Field("value", column.getFullyQualifiedJavaType());
fValue.setVisibility(JavaVisibility.PRIVATE);
fValue.setFinal(true);
commentGenerator.addFieldComment(fValue, introspectedTable);
innerEnum.addField(fValue);
Field fName = new Field("name", FullyQualifiedJavaType.getStringInstance());
fName.setVisibility(JavaVisibility.PRIVATE);
fName.setFinal(true);
commentGenerator.addFieldComment(fName, introspectedTable);
innerEnum.addField(fName);
Method mInc = new Method(enumName);
mInc.setConstructor(true);
mInc.addBodyLine("this.value = value;");
mInc.addBodyLine("this.name = name;");
mInc.addParameter(new Parameter(fValue.getType(), "value"));
mInc.addParameter(new Parameter(fName.getType(), "name"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mInc);
// 获取value的方法
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mValue);
Method mValue1 = JavaElementGeneratorTools.generateGetterMethod(fValue);
mValue1.setName("value");
commentGenerator.addGeneralMethodComment(mValue1, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mValue1);
// 获取name的方法
Method mName = JavaElementGeneratorTools.generateGetterMethod(fName);
commentGenerator.addGeneralMethodComment(mName, introspectedTable);
FormatTools.addMethodWithBestPosition(innerEnum, mName);
return innerEnum;
}
public class EnumItemInfo {
private IntrospectedColumn column;
private String name;
private String comment;
private String value;
public EnumItemInfo(IntrospectedColumn column, String name, String comment, String value) {
this.column = column;
this.name = name.trim();
this.comment = comment.trim();
this.value = value.trim();
}
/**
* Getter method for property <tt>comment</tt>.
* @return property value of comment
* @author hewei
*/
public String getComment() {
return "\"" + comment + "\"";
}
/**
* Getter method for property <tt>name</tt>.
* @return property value of name
* @author hewei
*/
public String getName() {
return name.toUpperCase();
}
/**
* Getter method for property <tt>value</tt>.
* @return property value of value
* @author hewei
*/
public String getValue() {
String javaType = this.column.getFullyQualifiedJavaType().getShortName();
if ("NULL".equalsIgnoreCase(value)) {
return "null";
} else {
return "new " + javaType + "(\"" + value + "\")";
}
}
/**
* Getter method for property <tt>value</tt>.
* @return property value of value
* @author hewei
*/
public String getOriginalValue() {
return value;
}
return value;
}
}
}
@@ -27,8 +27,8 @@ import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.internal.util.JavaBeansUtil;
import org.mybatis.generator.internal.util.StringUtility;
import java.sql.JDBCType;
import java.util.*;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
@@ -42,28 +42,70 @@ import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
* ---------------------------------------------------------------------------
*/
public class LogicalDeletePlugin extends BasePlugin {
public static final String METHOD_LOGICAL_DELETE_BY_EXAMPLE = "logicalDeleteByExample"; // 方法名
public static final String METHOD_LOGICAL_DELETE_BY_PRIMARY_KEY = "logicalDeleteByPrimaryKey"; // 方法名
public static final String METHOD_LOGICAL_DELETE_BY_EXAMPLE = "logicalDeleteByExample";
public static final String METHOD_LOGICAL_DELETE_BY_PRIMARY_KEY = "logicalDeleteByPrimaryKey";
public static final String PRO_LOGICAL_DELETE_COLUMN = "logicalDeleteColumn"; // 逻辑删除列-Key
public static final String PRO_LOGICAL_DELETE_VALUE = "logicalDeleteValue"; // 逻辑删除值-Key
public static final String PRO_LOGICAL_UN_DELETE_VALUE = "logicalUnDeleteValue"; // 逻辑删除未删除值-Key
public static final String PRO_LOGICAL_DELETE_COLUMN = "logicalDeleteColumn";
public static final String PRO_LOGICAL_DELETE_VALUE = "logicalDeleteValue";
public static final String PRO_LOGICAL_UN_DELETE_VALUE = "logicalUnDeleteValue";
public static final String PRO_LOGICAL_DELETE_CONST_NAME = "logicalDeleteConstName"; // 逻辑删除常量
public static final String PRO_LOGICAL_UN_DELETE_CONST_NAME = "logicalUnDeleteConstName"; // 逻辑删除常量
public static final String DEFAULT_LOGICAL_DELETE_CONST_NAME = "IS_DELETED"; // 逻辑删除标志位常量名称
public static final String DEFAULT_LOGICAL_UN_DELETE_CONST_NAME = "NOT_DELETED"; // 逻辑删除标志位常量名称(未删除)
/**
* 是否支持不推荐的常量配置方式
*/
public static final String PRO_ENABLE_LOGICAL_DELETE_CONST = "enableLogicalDeleteConst";
/**
* 逻辑删除常量
*/
public static final String PRO_LOGICAL_DELETE_CONST_NAME = "logicalDeleteConstName";
public static final String PRO_LOGICAL_UN_DELETE_CONST_NAME = "logicalUnDeleteConstName";
public static final String METHOD_LOGICAL_DELETED = "andLogicalDeleted"; // 逻辑删除查询方法
public static final String PARAMETER_LOGICAL_DELETED = METHOD_LOGICAL_DELETED; // 增强selectByPrimaryKey是参数名称
/**
* 逻辑删除标志位名称(默认)
*/
public static final String DEFAULT_LOGICAL_DELETE_NAME = "IS_DELETED";
public static final String DEFAULT_LOGICAL_UN_DELETE_NAME = "NOT_DELETED";
public static final String METHOD_SELECT_BY_PRIMARY_KEY_WITH_LOGICAL_DELETE = "selectByPrimaryKeyWithLogicalDelete"; // selectByPrimaryKey 的逻辑删除增强
/**
* 逻辑删除查询方法
*/
public static final String METHOD_LOGICAL_DELETED = "andLogicalDeleted";
/**
* 增强selectByPrimaryKey是参数名称
*/
public static final String PARAMETER_LOGICAL_DELETED = METHOD_LOGICAL_DELETED;
/**
* selectByPrimaryKey 的逻辑删除增强
*/
public static final String METHOD_SELECT_BY_PRIMARY_KEY_WITH_LOGICAL_DELETE = "selectByPrimaryKeyWithLogicalDelete";
private IntrospectedColumn logicalDeleteColumn; // 逻辑删除列
private String logicalDeleteValue; // 逻辑删除值
private String logicalUnDeleteValue; // 逻辑删除值(未删除)
private String logicalDeleteConstName; // 逻辑删除常量
private String logicalUnDeleteConstName; // 逻辑删除常量(未删除)
/**
* 逻辑删除列
*/
private IntrospectedColumn logicalDeleteColumn;
/**
* 逻辑删除值
*/
private String logicalDeleteValue;
/**
* 逻辑删除值(未删除)
*/
private String logicalUnDeleteValue;
/**
* 逻辑删除常量
*/
private String logicalDeleteConstName = DEFAULT_LOGICAL_DELETE_NAME;
/**
* 逻辑删除常量(未删除)
*/
private String logicalUnDeleteConstName = DEFAULT_LOGICAL_UN_DELETE_NAME;
/**
* 是否支持常量类型
*/
private Boolean enableLogicalDeleteConst;
/**
* 逻辑删除枚举
*/
private InnerEnum logicalDeleteEnum;
/**
* 初始化阶段
@@ -74,63 +116,85 @@ public class LogicalDeletePlugin extends BasePlugin {
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
// 1. 首先获取全局配置
// 1. 获取配置的逻辑删除列
Properties properties = getProperties();
String logicalDeleteColumn = properties.getProperty(PRO_LOGICAL_DELETE_COLUMN);
this.logicalDeleteValue = properties.getProperty(PRO_LOGICAL_DELETE_VALUE);
this.logicalUnDeleteValue = properties.getProperty(PRO_LOGICAL_UN_DELETE_VALUE);
// 2. 获取表单独配置,如果有则覆盖全局配置
if (introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_COLUMN) != null) {
logicalDeleteColumn = introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_COLUMN);
}
if (introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_VALUE) != null) {
this.logicalDeleteValue = introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_VALUE);
}
if (introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_UN_DELETE_VALUE) != null) {
this.logicalUnDeleteValue = introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_UN_DELETE_VALUE);
}
// 3. 判断该表是否存在逻辑删除列
this.logicalDeleteColumn = null;
List<IntrospectedColumn> columns = introspectedTable.getAllColumns();
for (IntrospectedColumn column : columns) {
if (column.getActualColumnName().equalsIgnoreCase(logicalDeleteColumn)) {
// 判断字段类型
JDBCType type = JDBCType.valueOf(column.getJdbcType());
if (JDBCType.BIGINT == type
|| JDBCType.BIT == type
|| JDBCType.BOOLEAN == type
|| JDBCType.CHAR == type
|| JDBCType.DOUBLE == type
|| JDBCType.FLOAT == type
|| JDBCType.INTEGER == type
|| JDBCType.LONGNVARCHAR == type
|| JDBCType.LONGVARCHAR == type
|| JDBCType.NCHAR == type
|| JDBCType.NVARCHAR == type
|| JDBCType.SMALLINT == type
|| JDBCType.TINYINT == type
|| JDBCType.VARCHAR == type) {
this.logicalDeleteColumn = column;
} else {
warnings.add("itfsw(逻辑删除插件):" + introspectedTable.getFullyQualifiedTable() + "逻辑删除列(" + introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_COLUMN) + ")的类型不在支持范围(请使用数字列,字符串列,布尔列)!");
}
}
}
this.logicalDeleteColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, logicalDeleteColumn);
// 判断如果表单独配置了逻辑删除列,但是却没有找到对应列进行提示
if (introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_COLUMN) != null && this.logicalDeleteColumn == null) {
warnings.add("itfsw(逻辑删除插件):" + introspectedTable.getFullyQualifiedTable() + "没有找到您配置的逻辑删除列(" + introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_COLUMN) + ")!");
}
// 4. 判断逻辑删除值是否配置了
if (this.logicalDeleteColumn != null && (this.logicalDeleteValue == null || this.logicalUnDeleteValue == null)) {
warnings.add("itfsw(逻辑删除插件):" + introspectedTable.getFullyQualifiedTable() + "没有找到您配置的逻辑删除值,请全局或者局部配置logicalDeleteValue和logicalUnDeleteValue值!");
// 2. 获取逻辑删除常量值
this.enableLogicalDeleteConst = properties.getProperty(PRO_ENABLE_LOGICAL_DELETE_CONST) == null ? true : StringUtility.isTrue(properties.getProperty(PRO_ENABLE_LOGICAL_DELETE_CONST));
if (this.enableLogicalDeleteConst) {
if (properties.getProperty(PRO_LOGICAL_DELETE_CONST_NAME) != null) {
this.logicalDeleteConstName = properties.getProperty(PRO_LOGICAL_DELETE_CONST_NAME).toUpperCase();
}
if (properties.getProperty(PRO_LOGICAL_UN_DELETE_CONST_NAME) != null) {
this.logicalUnDeleteConstName = properties.getProperty(PRO_LOGICAL_UN_DELETE_CONST_NAME).toUpperCase();
}
}
// 5. 获取逻辑删除常量值
this.logicalDeleteConstName = properties.getProperty(PRO_LOGICAL_DELETE_CONST_NAME) != null ? properties.getProperty(PRO_LOGICAL_DELETE_CONST_NAME).toUpperCase() : DEFAULT_LOGICAL_DELETE_CONST_NAME;
this.logicalUnDeleteConstName = properties.getProperty(PRO_LOGICAL_UN_DELETE_CONST_NAME) != null ? properties.getProperty(PRO_LOGICAL_UN_DELETE_CONST_NAME).toUpperCase() : DEFAULT_LOGICAL_UN_DELETE_CONST_NAME;
// 3. 优先借助 EnumTypeStatusPlugin 插件,去注解里面解析枚举
if (this.logicalDeleteColumn != null) {
EnumTypeStatusPlugin.EnumInfo enumInfo = null;
try {
enumInfo = new EnumTypeStatusPlugin.EnumInfo(this.logicalDeleteColumn);
// 解析注释
enumInfo.parseRemarks(this.logicalDeleteColumn.getRemarks());
} catch (EnumTypeStatusPlugin.EnumInfo.NotSupportTypeException e) {
this.logicalDeleteColumn = null;
warnings.add("itfsw(逻辑删除插件):" + introspectedTable.getFullyQualifiedTable() + "逻辑删除列(" + introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_COLUMN) + ")的类型不在支持范围(请使用数字列,字符串列,布尔列)!");
} catch (EnumTypeStatusPlugin.EnumInfo.CannotParseException e) {
// 这个异常不管,没有配置是正常的
} finally {
// 6. 防止增强的selectByPrimaryKey中逻辑删除键冲突
if (enumInfo != null) {
// 这个是注释里配置了枚举
if (enumInfo.hasItems() && enumInfo.getItems().size() >= 2) {
this.logicalUnDeleteValue = enumInfo.getItems().get(0).getOriginalValue();
this.logicalUnDeleteConstName = enumInfo.getItems().get(0).getName();
this.logicalDeleteValue = enumInfo.getItems().get(1).getOriginalValue();
this.logicalDeleteConstName = enumInfo.getItems().get(1).getName();
this.logicalDeleteEnum = enumInfo.generateEnum(commentGenerator, introspectedTable);
} else {
// 没有在注释里配置读取xml中配置的
this.logicalDeleteValue = properties.getProperty(PRO_LOGICAL_DELETE_VALUE);
this.logicalUnDeleteValue = properties.getProperty(PRO_LOGICAL_UN_DELETE_VALUE);
if (introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_VALUE) != null) {
this.logicalDeleteValue = introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_DELETE_VALUE);
}
if (introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_UN_DELETE_VALUE) != null) {
this.logicalUnDeleteValue = introspectedTable.getTableConfigurationProperty(PRO_LOGICAL_UN_DELETE_VALUE);
}
// 4. 判断逻辑删除值是否配置了
if (this.logicalDeleteValue == null || this.logicalUnDeleteValue == null) {
this.logicalDeleteColumn = null;
warnings.add("itfsw(逻辑删除插件):" + introspectedTable.getFullyQualifiedTable() + "没有找到您配置的逻辑删除值,请全局或者局部配置logicalDeleteValue和logicalUnDeleteValue值!");
} else {
// 兼容处理以前一些老用户配置的Long 和 Float配置问题
if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Long.class.getName())) {
this.logicalUnDeleteValue = this.logicalUnDeleteValue.replaceAll("L|l", "");
this.logicalDeleteValue = this.logicalDeleteValue.replaceAll("L|l", "");
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Float.class.getName())) {
this.logicalUnDeleteValue = this.logicalUnDeleteValue.replaceAll("F|f", "");
this.logicalDeleteValue = this.logicalDeleteValue.replaceAll("F|f", "");
}
enumInfo.addItem(this.logicalUnDeleteConstName, "未删除", this.logicalUnDeleteValue);
enumInfo.addItem(this.logicalDeleteConstName, "已删除", this.logicalDeleteValue);
this.logicalDeleteEnum = enumInfo.generateEnum(commentGenerator, introspectedTable);
}
}
}
}
}
// 5. 防止增强的selectByPrimaryKey中逻辑删除键冲突
if (this.logicalDeleteColumn != null) {
Field logicalDeleteField = JavaBeansUtil.getJavaBeansField(this.logicalDeleteColumn, context, introspectedTable);
if (logicalDeleteField.getName().equals(PARAMETER_LOGICAL_DELETED)) {
@@ -259,7 +323,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// 1. 逻辑删除ByExample
XmlElement logicalDeleteByExample = new XmlElement("update");
logicalDeleteByExample.addAttribute(new Attribute("id", METHOD_LOGICAL_DELETE_BY_EXAMPLE));
logicalDeleteByExample.addAttribute(new Attribute("parameterType", "map")); //$NON-NLS-2$
logicalDeleteByExample.addAttribute(new Attribute("parameterType", "map"));
commentGenerator.addComment(logicalDeleteByExample);
StringBuilder sb = new StringBuilder();
@@ -378,83 +442,21 @@ public class LogicalDeletePlugin extends BasePlugin {
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param field
* @param topLevelClass
* @param introspectedColumn
* @param introspectedTable
* @param modelClassType
* @return
*/
@Override
public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
this.generateModelMethodsAndFields(topLevelClass, introspectedTable);
return super.modelPrimaryKeyClassGenerated(topLevelClass, introspectedTable);
}
/**
* Model 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
this.generateModelMethodsAndFields(topLevelClass, introspectedTable);
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
/**
* 生成Model 逻辑删除相关方法和常量
* !!! bugfix:逻辑删除列作为复合主键的一部分的情况
* @param topLevelClass
* @param introspectedTable
*/
private void generateModelMethodsAndFields(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
if (this.logicalDeleteColumn != null) {
// 常量和逻辑删除方法跟随 逻辑删除列走
boolean flag = false;
for (Field field : topLevelClass.getFields()) {
if (this.logicalDeleteColumn.getJavaProperty().equals(field.getName())) {
flag = true;
break;
}
}
if (flag) {
ArrayList<Field> fields = (ArrayList<Field>) topLevelClass.getFields();
// 添加删除标志位常量
String logicalDeleteValue;
if (this.logicalDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalDeleteValue)) {
logicalDeleteValue = "null";
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getShortNameWithoutTypeArguments().equalsIgnoreCase("String")) {
logicalDeleteValue = "\"" + this.logicalDeleteValue + "\"";
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getShortNameWithoutTypeArguments().equalsIgnoreCase("Boolean")) {
logicalDeleteValue = (this.logicalDeleteValue.equals("1") || this.logicalDeleteValue.equalsIgnoreCase("true")) ? "true" : "false";
} else {
logicalDeleteValue = this.logicalDeleteValue;
}
Field logicalDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(this.logicalDeleteConstName, this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalDeleteValue);
commentGenerator.addFieldComment(logicalDeleteConstField, introspectedTable);
fields.add(0, logicalDeleteConstField);
// 添加删除标志位常量 DEL_FLAG_ON
String logicalUnDeleteValue;
if (this.logicalUnDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalUnDeleteValue)) {
logicalUnDeleteValue = "null";
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getShortNameWithoutTypeArguments().equalsIgnoreCase("String")) {
logicalUnDeleteValue = "\"" + this.logicalUnDeleteValue + "\"";
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getShortNameWithoutTypeArguments().equalsIgnoreCase("Boolean")) {
logicalUnDeleteValue = (this.logicalUnDeleteValue.equals("1") || this.logicalUnDeleteValue.equalsIgnoreCase("true")) ? "true" : "false";
} else {
logicalUnDeleteValue = this.logicalUnDeleteValue;
}
Field logicalUnDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(this.logicalUnDeleteConstName, this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalUnDeleteValue);
commentGenerator.addFieldComment(logicalUnDeleteConstField, introspectedTable);
fields.add(0, logicalUnDeleteConstField);
// ================================================= andLogicalDeleted =============================================
// 常量、枚举和逻辑删除方法跟随 逻辑删除列走
if (this.logicalDeleteColumn.getJavaProperty().equals(field.getName())) {
// 1. 添加枚举
topLevelClass.addInnerEnum(this.logicalDeleteEnum);
// 2. andLogicalDeleted 方法
Method mAndLogicalDeleted = JavaElementGeneratorTools.generateMethod(
METHOD_LOGICAL_DELETED,
JavaVisibility.PUBLIC,
@@ -463,10 +465,32 @@ public class LogicalDeletePlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mAndLogicalDeleted, introspectedTable);
Method logicalDeleteSetter = JavaBeansUtil.getJavaBeansSetter(this.logicalDeleteColumn, context, introspectedTable);
mAndLogicalDeleted.addBodyLine(logicalDeleteSetter.getName() + "(deleted ? " + this.logicalDeleteConstName + " : " + this.logicalUnDeleteConstName + ");");
mAndLogicalDeleted.addBodyLine(logicalDeleteSetter.getName() + "(deleted ? " + this.getEnumConstantValue(true) + " : " + this.getEnumConstantValue(false) + ");");
FormatTools.addMethodWithBestPosition(topLevelClass, mAndLogicalDeleted);
// 3. 添加逻辑删除常量
if (this.enableLogicalDeleteConst) {
Field logicalUnDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(
this.logicalUnDeleteConstName,
this.logicalDeleteColumn.getFullyQualifiedJavaType(),
this.getEnumConstantValue(false)
);
commentGenerator.addFieldComment(logicalUnDeleteConstField, introspectedTable);
Field logicalDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(
this.logicalDeleteConstName,
this.logicalDeleteColumn.getFullyQualifiedJavaType(),
this.getEnumConstantValue(true)
);
commentGenerator.addFieldComment(logicalDeleteConstField, introspectedTable);
// 常量放在字段开头
ArrayList<Field> fields = (ArrayList<Field>) topLevelClass.getFields();
fields.add(0, logicalUnDeleteConstField);
fields.add(0, logicalDeleteConstField);
}
}
}
return super.modelFieldGenerated(field, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
}
/**
@@ -480,8 +504,7 @@ public class LogicalDeletePlugin extends BasePlugin {
public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (this.logicalDeleteColumn != null) {
// 引入 Model类
FullyQualifiedJavaType model = introspectedTable.getRules().calculateAllFieldsClass();
topLevelClass.addImportedType(model);
topLevelClass.addImportedType(this.getColumnInModelType());
List<InnerClass> innerClasses = topLevelClass.getInnerClasses();
for (InnerClass innerClass : innerClasses) {
@@ -496,7 +519,7 @@ public class LogicalDeletePlugin extends BasePlugin {
StringBuffer sb = new StringBuffer();
sb.append("return deleted ? ");
String modelName = model.getShortName();
String modelName = this.getColumnInModelType().getShortName();
// 调用EqualTo方法
StringBuilder equalToMethodName = new StringBuilder();
@@ -505,7 +528,7 @@ public class LogicalDeletePlugin extends BasePlugin {
equalToMethodName.insert(0, "and");
equalToMethodName.append("EqualTo");
sb.append(equalToMethodName);
sb.append("(" + modelName + "." + this.logicalDeleteConstName + ")");
sb.append("(" + modelName + "." + this.getEnumConstantValue(true) + ")");
sb.append(" : ");
@@ -516,7 +539,7 @@ public class LogicalDeletePlugin extends BasePlugin {
notEqualToMethodName.insert(0, "and");
notEqualToMethodName.append("NotEqualTo");
sb.append(notEqualToMethodName);
sb.append("(" + modelName + "." + this.logicalDeleteConstName + ")");
sb.append("(" + modelName + "." + this.getEnumConstantValue(true) + ")");
sb.append(";");
@@ -526,6 +549,62 @@ public class LogicalDeletePlugin extends BasePlugin {
}
}
}
return true;
return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
}
/**
* 获取逻辑删除枚举
* @param delete
* @return
*/
private String getEnumConstantValue(boolean delete) {
if (this.logicalDeleteEnum != null) {
String enumConstant = this.logicalDeleteEnum.getEnumConstants().get(delete ? 1 : 0);
enumConstant = enumConstant.split("\\(")[0];
return this.logicalDeleteEnum.getType().getShortName() + "." + enumConstant + ".value()";
}
return null;
}
/**
* 获取逻辑删除列所在model(modelExampleClassGenerated执行顺序在前面!!!!!和官网上不一样,没办法只有自己去找)
* @return
*/
private FullyQualifiedJavaType getColumnInModelType() {
if (this.logicalDeleteColumn != null) {
IntrospectedTable introspectedTable = this.logicalDeleteColumn.getIntrospectedTable();
// primaryKey
for (IntrospectedColumn column : introspectedTable.getPrimaryKeyColumns()) {
if (column.getActualColumnName().equals(this.logicalDeleteColumn.getActualColumnName())) {
if (introspectedTable.getRules().generatePrimaryKeyClass()) {
return new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType());
} else {
return new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
}
}
}
// base record
for (IntrospectedColumn column : introspectedTable.getBaseColumns()) {
if (column.getActualColumnName().equals(this.logicalDeleteColumn.getActualColumnName())) {
if (introspectedTable.getRules().generateBaseRecordClass()) {
return new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
}
}
}
// blob record
for (IntrospectedColumn column : introspectedTable.getBLOBColumns()) {
if (column.getActualColumnName().equals(this.logicalDeleteColumn.getActualColumnName())) {
if (introspectedTable.getRules().generateRecordWithBLOBsClass()) {
return new FullyQualifiedJavaType(introspectedTable.getRecordWithBLOBsType());
} else {
return new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
}
}
}
}
return null;
}
}
@@ -352,19 +352,28 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
@Override
public boolean clientUpdateWithVersionByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
// column枚举,找出全字段对应的Model
FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
// issue#69 OptimisticLockerPlugin 插件updateWithVersionByExampleSelective方法的生成是基于updateByExampleSelective的,
// 这个方法在配置了SelectiveEnhancedPlugin时可能已经被先配置的SelectiveEnhancedPlugin改变了
if (!"selective".equals(method.getParameters().get(method.getParameters().size() - 1).getName())) {
// column枚举,找出全字段对应的Model
FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
}
return true;
}
@Override
public boolean clientUpdateWithVersionByPrimaryKeySelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
// column枚举,找出全字段对应的Model
FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
// issue#69 OptimisticLockerPlugin 插件updateWithVersionByExampleSelective方法的生成是基于updateByExampleSelective的,
// 这个方法在配置了SelectiveEnhancedPlugin时可能已经被先配置的SelectiveEnhancedPlugin改变了
if (!"selective".equals(method.getParameters().get(method.getParameters().size() - 1).getName())) {
// column枚举,找出全字段对应的Model
FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
}
return true;
}
@@ -24,6 +24,7 @@ import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.MyBatisGenerator;
import java.lang.reflect.Array;
import java.sql.ResultSet;
import java.util.List;
/**
@@ -155,9 +156,63 @@ public class BugFixedTest {
MyBatisGenerator generator = tool.generate(() -> DBHelper.createDB("scripts/BugFixedTest/issues-63.sql"));
for (GeneratedJavaFile file : generator.getGeneratedJavaFiles()) {
String fileName = file.getFileName();
if (fileName.startsWith("Repaydetail")){
if (fileName.startsWith("Repaydetail")) {
Assert.assertTrue("官方自己的问题", true);
}
}
}
/**
* 乐观锁插件配合SelectiveEnhancedPlugin多生成了selective参数的问题
* https://github.com/itfsw/mybatis-generator-plugin/issues/69
* @throws Exception
*/
@Test
public void issues69() throws Exception {
for (int i = 0; i < 2; i++) {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/BugFixedTest/issues-69-" + i + ".xml");
tool.generate(() -> DBHelper.createDB("scripts/BugFixedTest/issues-69.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", 1l);
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 1L);
tb.set("version", 152L);
tb.set("incF2", 10L);
tb.set("incF3", 5L);
// selective
ObjectUtil TbColumnId = new ObjectUtil(loader, packagz + ".Tb$Column#id");
ObjectUtil TbColumnVersion = new ObjectUtil(loader, packagz + ".Tb$Column#version");
ObjectUtil TbColumnIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#incF2");
Object columns = Array.newInstance(TbColumnId.getCls(), 3);
Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnVersion.getObject());
Array.set(columns, 2, TbColumnIncF2.getObject());
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateWithVersionByExampleSelective", 100L, tb.getObject(), tbExample.getObject(), columns);
Assert.assertEquals(sql, "update tb SET version = version + 1, id = 1 , inc_f2 = 10 WHERE version = 100 and ( ( id = '1' ) )");
// 执行一次,因为版本号100不存在所以应该返回0
Object result = tbMapper.invoke("updateWithVersionByExampleSelective", 100L, tb.getObject(), tbExample.getObject(), columns);
Assert.assertEquals(result, 0);
// id = 1 的版本号应该是0
result = tbMapper.invoke("updateWithVersionByExampleSelective", 0L, tb.getObject(), tbExample.getObject(), columns);
Assert.assertEquals(result, 1);
// 执行完成后版本号应该加1
ResultSet rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb where id = 1");
rs.first();
Assert.assertEquals(rs.getInt("version"), 1);
}
});
}
}
}
@@ -51,7 +51,7 @@ public class CommentPluginTest {
*/
@BeforeClass
public static void init() throws Exception {
DBHelper.createDB("scripts/ComentPlugin/init.sql");
DBHelper.createDB("scripts/CommentPlugin/init.sql");
}
/**
@@ -59,7 +59,7 @@ public class CommentPluginTest {
*/
@Test
public void testGenerateWithoutTemplate() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ComentPlugin/mybatis-generator-without-template.xml");
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/CommentPlugin/mybatis-generator-without-template.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
// 是否在使用系统默认模板
int count = 0;
@@ -76,7 +76,7 @@ public class CommentPluginTest {
*/
@Test
public void testGenerateWithTemplate() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ComentPlugin/mybatis-generator.xml");
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/CommentPlugin/mybatis-generator.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
// java中的注释
@@ -105,4 +105,31 @@ public class CommentPluginTest {
String comment = ((TextElement) els.get(0)).getContent();
Assert.assertEquals(comment, "addComment:BaseResultMap");
}
/**
* 测试配置了模板参数转换
*/
@Test
public void testGenerateWithOutComment() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/CommentPlugin/mybatis-generator-without-comment.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
// java中的注释
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
if (file.getFileName().equals("Tb.java")) {
TopLevelClass topLevelClass = (TopLevelClass) file.getCompilationUnit();
// addJavaFileComment
Assert.assertEquals(topLevelClass.getFileCommentLines().size(), 0);
// addFieldComment
Field id = topLevelClass.getFields().get(0);
Assert.assertEquals(id.getJavaDocLines().size(), 0);
// addGeneralMethodComment
Method cons = topLevelClass.getMethods().get(0);
Assert.assertEquals(cons.getJavaDocLines().size(), 0);
// addSetterComment
Method setter = topLevelClass.getMethods().get(5);
Assert.assertEquals(setter.getJavaDocLines().size(), 0);
}
}
}
}
@@ -61,7 +61,7 @@ public class EnumTypeStatusPluginTest {
tool = MyBatisGeneratorTool.create("scripts/EnumTypeStatusPlugin/mybatis-generator-with-unsupport-type.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件" + EnumTypeStatusPlugin.class.getTypeName() + "找到column为field2对应Java类型不是Short、Integer、Long、String!");
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件" + EnumTypeStatusPlugin.class.getTypeName() + "找到column为field2对应Java类型不在支持范围内!");
}
/**
@@ -226,4 +226,40 @@ public class LogicalDeletePluginTest {
}
});
}
/**
* 测试基于注释生成的逻辑删除枚举
* @throws Exception
*/
@Test
public void testWithRemarkEnum() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LogicalDeletePlugin/mybatis-generator-with-remarks-enum.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception{
// 验证是否已经按要求生成了枚举
ObjectUtil enumDelFlagEnable = new ObjectUtil(loader, packagz + ".TbRemark$DelFlag#ENABLE");
Assert.assertEquals(enumDelFlagEnable.invoke("value"), (short)1);
Assert.assertEquals(enumDelFlagEnable.invoke("getValue"), (short)1);
Assert.assertEquals(enumDelFlagEnable.invoke("getName"), "启用");
// 验证andLogicalDeleted方法
ObjectUtil tbRemark = new ObjectUtil(loader, packagz + ".TbRemark");
tbRemark.invoke("andLogicalDeleted", true);
Assert.assertEquals(tbRemark.get("delFlag"), (short)0);
tbRemark.invoke("andLogicalDeleted", false);
Assert.assertEquals(tbRemark.get("delFlag"), (short)1);
// 验证sql执行
ObjectUtil tbRemarkMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbRemarkMapper")));
ObjectUtil tbRemarkExample = new ObjectUtil(loader, packagz + ".TbRemarkExample");
ObjectUtil criteria = new ObjectUtil(tbRemarkExample.invoke("createCriteria"));
criteria.invoke("andLogicalDeleted", true);
String sql = SqlHelper.getFormatMapperSql(tbRemarkMapper.getObject(), "selectByExample", tbRemarkExample.getObject());
Assert.assertEquals(sql, "select id, del_flag from tb_remark WHERE ( del_flag = '0' )");
Object result = tbRemarkMapper.invoke("selectByExample", tbRemarkExample.getObject());
Assert.assertEquals(((List)result).size(), 1);
}
});
}
}
@@ -52,16 +52,12 @@ public abstract class AbstractShellCallback implements ShellCallback {
*/
@Override
public void refreshProject(String project) {
SqlSession sqlSession = null;
try {
// 编译项目
sqlSession = tool.compile();
// 编译项目
try (SqlSession sqlSession = tool.compile()){
reloadProject(sqlSession, tool.getTargetClassLoader(), tool.getTargetPackage());
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
} finally {
sqlSession.close();
}
}
@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2019.
~
~ 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">
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 乐观锁插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.OptimisticLockerPlugin"/>
<!-- 数据Model属性对应Column获取插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!-- Selective选择插入更新增强插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/>
<!--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="versionColumn" value="version"/>
</table>
</context>
</generatorConfiguration>
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2019.
~
~ 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">
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 数据Model属性对应Column获取插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!-- Selective选择插入更新增强插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/>
<!-- 乐观锁插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.OptimisticLockerPlugin"/>
<!--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="versionColumn" value="version"/>
</table>
</context>
</generatorConfiguration>
@@ -0,0 +1,37 @@
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50617
Source Host : localhost:3306
Source Database : mybatis-generator-plugin
Target Server Type : MYSQL
Target Server Version : 50617
File Encoding : 65001
Date: 2017-07-05 17:21:41
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`version` 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', '2', '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');
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2019.
~
~ 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.CommentPlugin"/>
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--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>
@@ -26,7 +26,7 @@
<!-- 插件 -->
<!-- 注释插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin">
<property name="template" value="src/test/resources/scripts/ComentPlugin/test-comment.ftl"/>
<property name="template" value="src/test/resources/scripts/CommentPlugin/test-comment.ftl"/>
</plugin>
<commentGenerator>
@@ -38,4 +38,24 @@ INSERT INTO `tb` VALUES ('6', 'f6', '100');
INSERT INTO `tb` VALUES ('7', 'f7', '100');
INSERT INTO `tb` VALUES ('8', 'f8', '100');
INSERT INTO `tb` VALUES ('9', 'f9', '100');
INSERT INTO `tb` VALUES ('10', 'f10', '100');
INSERT INTO `tb` VALUES ('10', 'f10', '100');
-- ----------------------------
-- Table structure for tb_all
-- ----------------------------
DROP TABLE IF EXISTS `tb_all`;
CREATE TABLE `tb_all` (
`key1` bigint(20) NOT NULL COMMENT '注释1',
`key2` varchar(20) NOT NULL COMMENT '注释2',
`field1` varchar(255) DEFAULT NULL COMMENT '注释3',
`field2` bigint(20) NOT NULL COMMENT '注释4',
`field3` longtext COMMENT '注释5',
PRIMARY KEY (`key1`, `key2`)
);
-- ----------------------------
-- Records of tb_all
-- ----------------------------
INSERT INTO `tb_all` VALUES ('1', 'key1', 'f1', '1', 'b1');
INSERT INTO `tb_all` VALUES ('2', 'key2', 'f2', '1', 'b2');
INSERT INTO `tb_all` VALUES ('3', 'key3', 'f3', '1', 'b3');
@@ -49,5 +49,6 @@
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_all"/>
</context>
</generatorConfiguration>
@@ -36,4 +36,19 @@ CREATE TABLE `tb` (
INSERT INTO `tb` VALUES ('1', '0', '0', null, 0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, null, null);
INSERT INTO `tb` VALUES ('2', '0', '1', null, 0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, null, null);
INSERT INTO `tb` VALUES ('3', '1', '0', null, 0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, null, null);
INSERT INTO `tb` VALUES ('5', '0', '0', null, 0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, null, null);
INSERT INTO `tb` VALUES ('5', '0', '0', null, 0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, null, null);
-- ----------------------------
-- Table structure for tb_remark
-- ----------------------------
DROP TABLE IF EXISTS `tb_remark`;
CREATE TABLE `tb_remark` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`del_flag` smallint(3) COMMENT '注释[enable(1):启用, disable(0):禁用]',
PRIMARY KEY (`id`)
);
-- ----------------------------
-- Records of tb_remark
-- ----------------------------
INSERT INTO `tb_remark` VALUES ('1', '0');
INSERT INTO `tb_remark` VALUES ('2', '1');
@@ -0,0 +1,51 @@
<?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.LogicalDeletePlugin">
<property name="logicalDeleteColumn" value="del_flag"/>
<property name="logicalDeleteValue" value="1"/>
<property name="logicalUnDeleteValue" value="0"/>
</plugin>
<!--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_remark">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>