Compare commits

..
15 Commits
31 changed files with 2380 additions and 252 deletions
+92 -1
View File
@@ -24,6 +24,7 @@
* [~~官方ConstructorBased配置BUG临时修正插件(ConstructorBasedBugFixPlugin)~~](#16-官方constructorbased配置bug临时修正插件)
* [乐观锁插件(OptimisticLockerPlugin)](#17-乐观锁插件)
* [表重命名配置插件(TableRenameConfigurationPlugin)](#18-表重命名配置插件)
* [Lombok插件(LombokPlugin)](#19-Lombok插件)
---------------------------------------
Maven引用:
@@ -31,7 +32,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.9</version>
<version>1.2.10</version>
</dependency>
```
---------------------------------------
@@ -65,6 +66,60 @@ MyBatis Generator 参考配置(插件依赖应该配置在mybatis-generator-ma
</plugin>
```
---------------------------------------
gradle集成[[issues#41]](https://github.com/itfsw/mybatis-generator-plugin/issues/41)),感谢[masa-kunikata](https://github.com/masa-kunikata)提供的脚本。
```gradle
// https://gist.github.com/masa-kunikata/daaf0f51a8ab9b808f61805407e1654c
buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "gradle.plugin.com.arenagod.gradle:mybatis-generator-plugin:1.4"
}
}
apply plugin: 'java-library'
apply plugin: "com.arenagod.gradle.MybatisGenerator"
apply plugin: 'eclipse'
sourceCompatibility = 1.8
targetCompatibility = 1.8
def mybatisGeneratorCore = 'org.mybatis.generator:mybatis-generator-core:1.3.7'
def itfswMybatisGeneratorPlugin = 'com.itfsw:mybatis-generator-plugin:1.2.10'
mybatisGenerator {
verbose = false
configFile = "config/mybatisGenerator/generatorConfig.xml"
dependencies {
mybatisGenerator project(':')
mybatisGenerator itfswMybatisGeneratorPlugin
mybatisGenerator mybatisGeneratorCore
}
}
repositories {
mavenCentral()
}
dependencies {
compile mybatisGeneratorCore
compile itfswMybatisGeneratorPlugin
testCompile 'junit:junit:4.12'
}
def defaultEncoding = 'UTF-8'
compileJava {
options.encoding = defaultEncoding
}
compileTestJava {
options.encoding = defaultEncoding
}
```
---------------------------------------
### 1. 查询单条数据插件
对应表Mapper接口增加了方法
插件:
@@ -228,6 +283,7 @@ public class Test {
* Example增强了setOrderByClause方法,新增orderBy(String orderByClause)方法直接返回example,增强链式调用,可以一路.下去了。
* 继续增强orderBy(String orderByClause)方法,增加orderBy(String ... orderByClauses)方法,配合数据Model属性对应Column获取插件(ModelColumnPlugin)使用效果更佳。
* 增加基于column的操作,当配置了[数据Model属性对应Column获取插件(ModelColumnPlugin)](#8-数据model属性对应column获取插件)插件时,提供column之间的比对操作。
* 增加createCriteria静态方法newAndCreateCriteria简写example的创建。
插件:
```xml
@@ -315,6 +371,19 @@ public class Test {
.andField1LessThanOrEqualToColumn(Tb.Column.field2) // where field1 <= field2
.example()
);
// ---------------------------- static createCriteria -----------------------
// simple
this.tbMapper.selectByExample(
new TbExample()
.createCriteria()
.example()
);
// new
this.tbMapper.selectByExample(
TbExample.newAndCreateCriteria()
.example()
);
}
}
```
@@ -1293,3 +1362,25 @@ public class Test {
</plugin>
</xml>
```
### 19. Lombok插件
使用Lombok的使用可以减少很多重复代码的书写,目前项目中已大量使用。
但Lombok的@Builder对于类的继承支持很不好,最近发现新版(>=1.18.2)已经提供了对@SuperBuilder的支持,所以新增该插件方便简写代码。
>warning: 目前很多IDE工具对@SuperBuilder支持不是很好,虽不影响正常使用,但是开发时很不友好,暂时可以使用ModelBuilderPlugin代替该功能。
>warning1: @Builder注解在Lombok 版本 >= 1.18.2 的情况下才能开启,对于存在继承关系的model会自动替换成@SuperBuilder注解。
>warning2: 配合插件IncrementsPlugin 并且 @Builder开启的情况下,因为@SuperBuilder的一些限制,
插件模拟Lombok插件生成了一些附加代码可能在某些编译器上会提示错误,请忽略(Lombok = 1.18.2 已测试)。
```xml
<xml>
<!-- Lombok插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.LombokPlugin">
<!-- @Builder 必须在 Lombok 版本 >= 1.18.2 的情况下 -->
<property name="@Builder" value="false"/>
<!-- @NoArgsConstructor 和 @AllArgsConstructor 使用规则和Lombok一致 -->
<property name="@AllArgsConstructor" value="false"/>
<property name="@NoArgsConstructor" value="false"/>
</plugin>
</xml>
```
+19 -3
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.10</version>
<version>1.2.11</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -32,7 +32,7 @@
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
<version>1.3.7</version>
<scope>provided</scope>
</dependency>
<!-- 日志 -->
@@ -89,6 +89,22 @@
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>[1.18.2,)</version>
<scope>test</scope>
</dependency>
<!-- lombok dependency -->
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8</version>
<scope>system</scope>
<!-- jdk path -->
<systemPath>${env.JAVA_HOME}/lib/tools.jar</systemPath>
</dependency>
</dependencies>
@@ -217,7 +233,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.10</tag>
<tag>V1.2.11</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -22,6 +22,8 @@ import java.util.List;
* ---------------------------------------------------------------------------
*/
public class ExampleEnhancedPlugin extends BasePlugin {
public static final String METHOD_NEW_AND_CREATE_CRITERIA = "newAndCreateCriteria"; // newAndCreateCriteria 方法
private boolean enableColumnOperate = false; // 是否启用column的操作
/**
@@ -67,11 +69,34 @@ public class ExampleEnhancedPlugin extends BasePlugin {
}
// orderBy方法
addOrderByMethodToExample(topLevelClass, introspectedTable);
this.addOrderByMethodToExample(topLevelClass, introspectedTable);
// createCriteria 静态方法
this.addStaticCreateCriteriaMethodToExample(topLevelClass, introspectedTable);
return true;
}
/**
* 添加 createCriteria 静态方法
* @param topLevelClass
* @param introspectedTable
*/
private void addStaticCreateCriteriaMethodToExample(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
Method createCriteriaMethod = JavaElementGeneratorTools.generateMethod(
METHOD_NEW_AND_CREATE_CRITERIA,
JavaVisibility.PUBLIC,
FullyQualifiedJavaType.getCriteriaInstance()
);
commentGenerator.addGeneralMethodComment(createCriteriaMethod, introspectedTable);
createCriteriaMethod.setStatic(true);
createCriteriaMethod.addBodyLine(topLevelClass.getType().getShortName() + " example = new " + topLevelClass.getType().getShortName() + "();");
createCriteriaMethod.addBodyLine("return example.createCriteria();");
FormatTools.addMethodWithBestPosition(topLevelClass, createCriteriaMethod);
}
/**
* 添加列操作方法
* @param topLevelClass
@@ -17,7 +17,9 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.SpecTypeArgumentsFullyQualifiedJavaType;
import com.itfsw.mybatis.generator.plugins.utils.hook.IIncrementsPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.ILombokPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IModelBuilderPluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
@@ -28,6 +30,7 @@ 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.util.ArrayList;
import java.util.List;
@@ -40,11 +43,14 @@ import java.util.List;
* @time:2017/6/19 15:20
* ---------------------------------------------------------------------------
*/
public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginHook, IIncrementsPluginHook {
public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginHook, IIncrementsPluginHook, ILombokPluginHook {
public static final String PRO_INCREMENTS_COLUMNS = "incrementsColumns"; // incrementsColumns property
public static final String FIELD_INC_MAP = "incrementsColumnsInfoMap"; // 为了防止和用户数据库字段冲突,特殊命名
public static final String METHOD_INC_CHECK = "hasIncsForColumn"; // inc 检查方法名称
private IncrementsPluginTools incTools; // 增量插件工具
private List<IntrospectedColumn> incColumns; // 表启用增量操作的字段
private InnerEnum incEnum; // 增量Enum
private InnerClass incEnumBuilder; // 添加了增量Enum的builder
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
@@ -55,8 +61,8 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
public boolean validate(List<String> warnings) {
// 插件使用前提是使用了ModelBuilderPlugin插件
if (!PluginTools.checkDependencyPlugin(getContext(), ModelBuilderPlugin.class)) {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件需配合com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin插件使用!");
if (!(PluginTools.checkDependencyPlugin(getContext(), ModelBuilderPlugin.class) || PluginTools.checkDependencyPlugin(getContext(), LombokPlugin.class))) {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件需配合" + ModelBuilderPlugin.class.getTypeName() + "或者" + LombokPlugin.class.getTypeName() + "插件使用!");
return false;
}
@@ -70,7 +76,23 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
this.incTools = IncrementsPluginTools.getTools(context, introspectedTable, warnings);
this.incColumns = new ArrayList<>();
this.incEnum = null;
this.incEnumBuilder = null;
String incrementsColumns = introspectedTable.getTableConfigurationProperty(IncrementsPlugin.PRO_INCREMENTS_COLUMNS);
if (StringUtility.stringHasValue(incrementsColumns)) {
// 切分
String[] incrementsColumnsStrs = incrementsColumns.split(",");
for (String incrementsColumnsStr : incrementsColumnsStrs) {
IntrospectedColumn column = IntrospectedTableTools.safeGetColumn(introspectedTable, incrementsColumnsStr);
if (column == null) {
warnings.add("itfsw:插件" + IncrementsPlugin.class.getTypeName() + "插件没有找到column为" + incrementsColumnsStr.trim() + "的字段!");
} else {
incColumns.add(column);
}
}
}
}
/**
@@ -145,6 +167,219 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
return super.sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(element, introspectedTable);
}
// =============================================== ILombokPluginHook ===================================================
@Override
public boolean modelBaseRecordBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
return this.lombokBuilderClassGenerated(topLevelClass, columns, introspectedTable);
}
@Override
public boolean modelPrimaryKeyBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
return this.lombokBuilderClassGenerated(topLevelClass, columns, introspectedTable);
}
@Override
public boolean modelRecordWithBLOBsBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
return this.lombokBuilderClassGenerated(topLevelClass, columns, introspectedTable);
}
/**
* Lombok Builder 生成
* @param topLevelClass
* @param columns
* @param introspectedTable
* @return
*/
private boolean lombokBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
if (this.support()) {
boolean find = false;
for (IntrospectedColumn column : columns) {
if (this.supportColumn(column)) {
find = true;
break;
}
}
if (find) {
// ----------------------------------- topLevelClass 方法 --------------------------------
FullyQualifiedJavaType builderType = new FullyQualifiedJavaType(topLevelClass.getType().getShortName() + "." + topLevelClass.getType().getShortName() + "Builder");
builderType.addTypeArgument(new SpecTypeArgumentsFullyQualifiedJavaType("<?, ?>"));
// 增加构造函数
Method constructor = new Method(topLevelClass.getType().getShortName());
commentGenerator.addGeneralMethodComment(constructor, introspectedTable);
constructor.setVisibility(JavaVisibility.PROTECTED);
constructor.setConstructor(true);
constructor.addParameter(new Parameter(builderType, "builder"));
// 是否调用父类构造函数
if (topLevelClass.getSuperClass() != null) {
constructor.addBodyLine("super(builder);");
}
for (IntrospectedColumn column : columns) {
Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable);
constructor.addBodyLine("this." + field.getName() + " = builder." + field.getName() + ";");
}
FormatTools.addMethodWithBestPosition(topLevelClass, constructor);
// 增加静态builder方法实现和lombok一样
Method builderMethod = JavaElementGeneratorTools.generateMethod(
"builder",
JavaVisibility.PUBLIC,
builderType
);
commentGenerator.addGeneralMethodComment(builderMethod, introspectedTable);
builderMethod.setStatic(true);
builderMethod.addBodyLine("return new " + topLevelClass.getType().getShortName() + "." + topLevelClass.getType().getShortName() + "BuilderImpl();");
FormatTools.addMethodWithBestPosition(topLevelClass, builderMethod);
// ------------------------------ builder Class ----------------------------------
InnerClass builderCls = new InnerClass(topLevelClass.getType().getShortName() + "Builder");
commentGenerator.addClassComment(builderCls, introspectedTable);
builderCls.setVisibility(JavaVisibility.PUBLIC);
builderCls.setStatic(true);
builderCls.setAbstract(true);
builderCls.getType().addTypeArgument(
new SpecTypeArgumentsFullyQualifiedJavaType("<C extends " + topLevelClass.getType().getShortName()
+ ", B extends " + topLevelClass.getType().getShortName()
+ "." + topLevelClass.getType().getShortName() + "Builder<C, B>>")
);
if (topLevelClass.getSuperClass() != null) {
FullyQualifiedJavaType superBuilderCls = new FullyQualifiedJavaType(topLevelClass.getSuperClass().getShortName() + "Builder");
superBuilderCls.addTypeArgument(new SpecTypeArgumentsFullyQualifiedJavaType("<C, B>"));
builderCls.setSuperClass(superBuilderCls);
}
// 类注解
topLevelClass.addImportedType(LombokPlugin.EnumLombokAnnotations.SETTER.getClazz());
builderCls.addAnnotation(LombokPlugin.EnumLombokAnnotations.SETTER.getAnnotation());
topLevelClass.addImportedType(LombokPlugin.EnumLombokAnnotations.ACCESSORS_FLUENT_TRUE.getClazz());
builderCls.addAnnotation(LombokPlugin.EnumLombokAnnotations.ACCESSORS_FLUENT_TRUE.getAnnotation());
if (topLevelClass.getSuperClass() != null) {
topLevelClass.addImportedType(LombokPlugin.EnumLombokAnnotations.TO_STRING_CALL_SUPER.getClazz());
builderCls.addAnnotation(LombokPlugin.EnumLombokAnnotations.TO_STRING_CALL_SUPER.getAnnotation());
} else {
topLevelClass.addImportedType(LombokPlugin.EnumLombokAnnotations.TO_STRING.getClazz());
builderCls.addAnnotation(LombokPlugin.EnumLombokAnnotations.TO_STRING.getAnnotation());
}
for (IntrospectedColumn introspectedColumn : columns) {
Field field = JavaBeansUtil.getJavaBeansField(introspectedColumn, context, introspectedTable);
field.getJavaDocLines().clear();
commentGenerator.addFieldComment(field, introspectedTable);
builderCls.addField(field);
}
// self 方法
Method selfMethod1 = JavaElementGeneratorTools.generateMethod(
"self",
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("B")
);
commentGenerator.addGeneralMethodComment(selfMethod1, introspectedTable);
FormatTools.addMethodWithBestPosition(builderCls, selfMethod1);
// build 方法
Method buildMethod1 = JavaElementGeneratorTools.generateMethod(
"build",
JavaVisibility.PUBLIC,
new FullyQualifiedJavaType("C")
);
commentGenerator.addGeneralMethodComment(buildMethod1, introspectedTable);
FormatTools.addMethodWithBestPosition(builderCls, buildMethod1);
topLevelClass.addInnerClass(builderCls);
// --------------------------------- 生成自增插件需要的方法 --------------------------------------
// 增加枚举
if (this.incEnum == null) {
this.incEnum = this.generatedIncEnum(introspectedTable);
this.incEnumBuilder = builderCls;
builderCls.addInnerEnum(this.incEnum);
// topLevel class 添加必要的操作方法
this.addIncMethodToTopLevelClass(topLevelClass, builderCls, introspectedTable, true);
// Builder 中 添加字段支持
Field fIncrements = JavaElementGeneratorTools.generateField(
IncrementsPlugin.FIELD_INC_MAP,
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("Map<String, " + this.getIncEnum(builderCls, introspectedTable).getFullyQualifiedName() + ">"),
"new HashMap<String, " + this.getIncEnum(builderCls, introspectedTable).getFullyQualifiedName() + ">()"
);
commentGenerator.addFieldComment(fIncrements, introspectedTable);
builderCls.addField(fIncrements);
// Builder 构造函数增加 自增Map
constructor.addBodyLine("this." + IncrementsPlugin.FIELD_INC_MAP + " = builder." + IncrementsPlugin.FIELD_INC_MAP + ";");
}
FullyQualifiedJavaType builderType2 = new FullyQualifiedJavaType(topLevelClass.getType().getShortName() + "." + topLevelClass.getType().getShortName() + "Builder");
builderType2.addTypeArgument(new SpecTypeArgumentsFullyQualifiedJavaType("<C, B>"));
for (IntrospectedColumn column : columns) {
if (this.supportColumn(column)) {
Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable);
// 增加方法
Method mIncrements = JavaElementGeneratorTools.generateMethod(
field.getName(),
JavaVisibility.PUBLIC,
builderType2,
new Parameter(field.getType(), field.getName()),
new Parameter(this.getIncEnum(builderCls, introspectedTable), "inc")
);
commentGenerator.addSetterComment(mIncrements, introspectedTable, column);
mIncrements.addBodyLine("this." + IncrementsPlugin.FIELD_INC_MAP + ".put(\"" + column.getActualColumnName() + "\", inc);");
mIncrements.addBodyLine("return this." + field.getName() + "(" + field.getName() + ");");
FormatTools.addMethodWithBestPosition(builderCls, mIncrements);
}
}
// ------------------------------ builderImpl Class ----------------------------------
InnerClass builderImplCls = new InnerClass(topLevelClass.getType().getShortName() + "BuilderImpl");
commentGenerator.addClassComment(builderImplCls, introspectedTable);
FullyQualifiedJavaType builderType1 = new FullyQualifiedJavaType(topLevelClass.getType().getShortName() + "." + topLevelClass.getType().getShortName() + "Builder");
builderType1.addTypeArgument(new SpecTypeArgumentsFullyQualifiedJavaType(
"<" + topLevelClass.getType().getShortName() + ", " + topLevelClass.getType().getShortName() + "." + topLevelClass.getType().getShortName() + "BuilderImpl" + ">"
));
builderImplCls.setSuperClass(builderType1);
builderImplCls.setVisibility(JavaVisibility.PRIVATE);
builderImplCls.setFinal(true);
builderImplCls.setStatic(true);
topLevelClass.addInnerClass(builderImplCls);
// self 方法
Method selfMethod = JavaElementGeneratorTools.generateMethod(
"self",
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType(topLevelClass.getType().getShortName() + "." + topLevelClass.getType().getShortName() + "BuilderImpl")
);
commentGenerator.addGeneralMethodComment(selfMethod, introspectedTable);
selfMethod.addBodyLine("return this;");
FormatTools.addMethodWithBestPosition(builderImplCls, selfMethod);
// build 方法
Method buildMethod = JavaElementGeneratorTools.generateMethod(
"build",
JavaVisibility.PUBLIC,
topLevelClass.getType()
);
commentGenerator.addGeneralMethodComment(buildMethod, introspectedTable);
buildMethod.addBodyLine("return new " + topLevelClass.getType().getShortName() + "(this);");
FormatTools.addMethodWithBestPosition(builderImplCls, buildMethod);
return false;
}
}
return true;
}
// =============================================== IModelBuilderPluginHook ===================================================
/**
@@ -157,65 +392,20 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
*/
@Override
public boolean modelBuilderClassGenerated(TopLevelClass topLevelClass, InnerClass builderClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
if (incTools.support()) {
// 增加枚举
InnerEnum eIncrements = new InnerEnum(new FullyQualifiedJavaType("Inc"));
eIncrements.setVisibility(JavaVisibility.PUBLIC);
eIncrements.setStatic(true);
eIncrements.addEnumConstant("INC(\"+\")");
eIncrements.addEnumConstant("DEC(\"-\")");
commentGenerator.addEnumComment(eIncrements, introspectedTable);
// 生成属性和构造函数
Field fValue = new Field("value", FullyQualifiedJavaType.getStringInstance());
fValue.setVisibility(JavaVisibility.PRIVATE);
fValue.setFinal(true);
commentGenerator.addFieldComment(fValue, introspectedTable);
eIncrements.addField(fValue);
if (this.support()) {
if (this.incEnum == null) {
this.incEnum = this.generatedIncEnum(introspectedTable);
this.incEnumBuilder = builderClass;
// 增加枚举
builderClass.addInnerEnum(this.incEnum);
// topLevel class 添加必要的操作方法
this.addIncMethodToTopLevelClass(topLevelClass, builderClass, introspectedTable, false);
}
Method mInc = new Method("Inc");
mInc.setConstructor(true);
mInc.addBodyLine("this.value = value;");
mInc.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "value"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
FormatTools.addMethodWithBestPosition(eIncrements, mInc);
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
FormatTools.addMethodWithBestPosition(eIncrements, mValue);
builderClass.addInnerEnum(eIncrements);
// 增加field
Field fIncrements = JavaElementGeneratorTools.generateField(
IncrementsPlugin.FIELD_INC_MAP,
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("Map<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">"),
"new HashMap<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">()"
);
commentGenerator.addFieldComment(fIncrements, introspectedTable);
topLevelClass.addField(fIncrements);
topLevelClass.addImportedType("java.util.Map");
topLevelClass.addImportedType("java.util.HashMap");
// getter&setter
Method mGetter = JavaElementGeneratorTools.generateGetterMethod(fIncrements);
commentGenerator.addGetterComment(mGetter, introspectedTable, null);
FormatTools.addMethodWithBestPosition(topLevelClass, mGetter);
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
FormatTools.addMethodWithBestPosition(topLevelClass, mSetter);
// 增加判断方法
Method mHasIncsForColumn = JavaElementGeneratorTools.generateMethod(
IncrementsPlugin.METHOD_INC_CHECK,
JavaVisibility.PUBLIC,
FullyQualifiedJavaType.getBooleanPrimitiveInstance(),
new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")
);
commentGenerator.addGeneralMethodComment(mHasIncsForColumn, introspectedTable);
mHasIncsForColumn.addBodyLine("return " + IncrementsPlugin.FIELD_INC_MAP + ".get(column) != null;");
FormatTools.addMethodWithBestPosition(topLevelClass, mHasIncsForColumn);
// Builder 中 添加字段支持
for (IntrospectedColumn column : columns) {
if (incTools.supportColumn(column)) {
if (this.supportColumn(column)) {
Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable);
// 增加方法
Method mIncrements = JavaElementGeneratorTools.generateMethod(
@@ -223,7 +413,7 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
JavaVisibility.PUBLIC,
builderClass.getType(),
new Parameter(field.getType(), field.getName()),
new Parameter(incTools.getIncEnum(), "inc")
new Parameter(this.getIncEnum(builderClass, introspectedTable), "inc")
);
commentGenerator.addSetterComment(mIncrements, introspectedTable, column);
@@ -266,7 +456,7 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
public List<Element> incrementSetElementGenerated(IntrospectedColumn introspectedColumn, String prefix, boolean hasComma) {
List<Element> list = new ArrayList<>();
if (incTools.supportColumn(introspectedColumn)) {
if (this.supportColumn(introspectedColumn)) {
// 1. column = 节点
list.add(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = "));
@@ -313,10 +503,10 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
*/
@Override
public Element incrementSetsWithSelectiveEnhancedPluginElementGenerated(IntrospectedColumn versionColumn) {
if (incTools.support()) {
if (this.support()) {
XmlElement choose = new XmlElement("choose");
for (IntrospectedColumn introspectedColumn : incTools.getColumns()) {
for (IntrospectedColumn introspectedColumn : this.incColumns) {
if (versionColumn == null || !introspectedColumn.getActualColumnName().equals(versionColumn.getActualColumnName())) {
XmlElement when = new XmlElement("when");
@@ -356,12 +546,86 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
// =================================================== 原生方法的支持 ====================================================
/**
* 向topLevelClass 添加必要的操作函数
* @param topLevelClass
* @param builderCls
* @param introspectedTable
* @param withLombok
*/
private void addIncMethodToTopLevelClass(TopLevelClass topLevelClass, InnerClass builderCls, IntrospectedTable introspectedTable, boolean withLombok) {
// 增加field
Field fIncrements = JavaElementGeneratorTools.generateField(
IncrementsPlugin.FIELD_INC_MAP,
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("Map<String, " + this.getIncEnum(builderCls, introspectedTable).getFullyQualifiedName() + ">"),
"new HashMap<String, " + this.getIncEnum(builderCls, introspectedTable).getFullyQualifiedName() + ">()"
);
commentGenerator.addFieldComment(fIncrements, introspectedTable);
topLevelClass.addField(fIncrements);
topLevelClass.addImportedType("java.util.Map");
topLevelClass.addImportedType("java.util.HashMap");
// getter&setter
if (!withLombok) {
Method mGetter = JavaElementGeneratorTools.generateGetterMethod(fIncrements);
commentGenerator.addGetterComment(mGetter, introspectedTable, null);
FormatTools.addMethodWithBestPosition(topLevelClass, mGetter);
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
FormatTools.addMethodWithBestPosition(topLevelClass, mSetter);
}
// 增加判断方法
Method mHasIncsForColumn = JavaElementGeneratorTools.generateMethod(
IncrementsPlugin.METHOD_INC_CHECK,
JavaVisibility.PUBLIC,
FullyQualifiedJavaType.getBooleanPrimitiveInstance(),
new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")
);
commentGenerator.addGeneralMethodComment(mHasIncsForColumn, introspectedTable);
mHasIncsForColumn.addBodyLine("return " + IncrementsPlugin.FIELD_INC_MAP + ".get(column) != null;");
FormatTools.addMethodWithBestPosition(topLevelClass, mHasIncsForColumn);
}
/**
* 生成Inc enum
* @param introspectedTable
* @return
*/
private InnerEnum generatedIncEnum(IntrospectedTable introspectedTable) {
// 增加枚举
InnerEnum eIncrements = new InnerEnum(new FullyQualifiedJavaType("Inc"));
eIncrements.setVisibility(JavaVisibility.PUBLIC);
eIncrements.setStatic(true);
eIncrements.addEnumConstant("INC(\"+\")");
eIncrements.addEnumConstant("DEC(\"-\")");
commentGenerator.addEnumComment(eIncrements, introspectedTable);
// 生成属性和构造函数
Field fValue = new Field("value", FullyQualifiedJavaType.getStringInstance());
fValue.setVisibility(JavaVisibility.PRIVATE);
fValue.setFinal(true);
commentGenerator.addFieldComment(fValue, introspectedTable);
eIncrements.addField(fValue);
Method mInc = new Method("Inc");
mInc.setConstructor(true);
mInc.addBodyLine("this.value = value;");
mInc.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "value"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
FormatTools.addMethodWithBestPosition(eIncrements, mInc);
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
FormatTools.addMethodWithBestPosition(eIncrements, mValue);
return eIncrements;
}
/**
* 有Selective代码生成
* @param element
*/
private void generatedWithSelective(XmlElement element, IntrospectedTable introspectedTable, boolean hasPrefix) {
if (incTools.support()) {
if (this.support()) {
// 查找 set->if->text
List<XmlElement> sets = XmlElementTools.findXmlElements(element, "set");
if (sets.size() > 0) {
@@ -393,7 +657,7 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
* @param hasPrefix
*/
private void generatedWithoutSelective(XmlElement xmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) {
if (incTools.support()) {
if (this.support()) {
List<Element> newEles = new ArrayList<>();
for (Element ele : xmlElement.getElements()) {
// 找到text节点且格式为 set xx = xx 或者 xx = xx
@@ -421,4 +685,40 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
xmlElement.getElements().addAll(newEles);
}
}
/**
* 获取INC Enum
* @param builderCls
* @return
*/
private FullyQualifiedJavaType getIncEnum(InnerClass builderCls, IntrospectedTable introspectedTable) {
try {
return new FullyQualifiedJavaType(BeanUtils.getProperty(this.incEnumBuilder.getType(), "baseShortName").toString() + "." + this.incEnum.getType().getShortName());
} catch (Exception e) {
logger.error("获取Inc enum 失败!", e);
}
return null;
}
/**
* 是否启用了
* @return
*/
private boolean support() {
return this.incColumns.size() > 0;
}
/**
* 判断是否为需要进行增量操作的column
* @param searchColumn
* @return
*/
private boolean supportColumn(IntrospectedColumn searchColumn) {
for (IntrospectedColumn column : this.incColumns) {
if (column.getActualColumnName().equals(searchColumn.getActualColumnName())) {
return true;
}
}
return false;
}
}
@@ -16,10 +16,8 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.FormatTools;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.ILogicalDeletePluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
@@ -102,14 +100,12 @@ public class LogicalDeletePlugin extends BasePlugin {
|| JDBCType.BIT == type
|| JDBCType.BOOLEAN == type
|| JDBCType.CHAR == type
|| JDBCType.DECIMAL == type
|| JDBCType.DOUBLE == type
|| JDBCType.FLOAT == type
|| JDBCType.INTEGER == type
|| JDBCType.LONGNVARCHAR == type
|| JDBCType.LONGVARCHAR == type
|| JDBCType.NCHAR == type
|| JDBCType.NUMERIC == type
|| JDBCType.NVARCHAR == type
|| JDBCType.SMALLINT == type
|| JDBCType.TINYINT == type
@@ -168,6 +164,8 @@ public class LogicalDeletePlugin extends BasePlugin {
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mLogicalDeleteByExample);
logger.debug("itfsw(逻辑删除插件):" + interfaze.getType().getShortName() + "增加方法logicalDeleteByExample。");
// hook
PluginTools.getHook(ILogicalDeletePluginHook.class).clientLogicalDeleteByExampleMethodGenerated(mLogicalDeleteByExample, interfaze, introspectedTable);
// 2. 判断是否有主键,生成主键删除方法
if (introspectedTable.hasPrimaryKeyColumns()) {
@@ -232,6 +230,8 @@ public class LogicalDeletePlugin extends BasePlugin {
interfaze.addImportedTypes(importedTypes);
FormatTools.addMethodWithBestPosition(interfaze, mLogicalDeleteByPrimaryKey);
logger.debug("itfsw(逻辑删除插件):" + interfaze.getType().getShortName() + "增加方法logicalDeleteByPrimaryKey。");
// hook
PluginTools.getHook(ILogicalDeletePluginHook.class).clientLogicalDeleteByPrimaryKeyMethodGenerated(mLogicalDeleteByPrimaryKey, interfaze, introspectedTable);
// 增强selectByPrimaryKey
mSelectByPrimaryKey.addParameter(new Parameter(
@@ -269,29 +269,15 @@ public class LogicalDeletePlugin extends BasePlugin {
// 更新逻辑删除字段
sb.append(this.logicalDeleteColumn.getActualColumnName());
sb.append(" = ");
// 判断字段类型
JDBCType type = JDBCType.valueOf(this.logicalDeleteColumn.getJdbcType());
if (this.logicalDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalDeleteValue)) {
sb.append("NULL");
} else if (JDBCType.CHAR == type
|| JDBCType.LONGNVARCHAR == type
|| JDBCType.LONGVARCHAR == type
|| JDBCType.NCHAR == type
|| JDBCType.NVARCHAR == type
|| JDBCType.VARCHAR == type) {
sb.append("'");
sb.append(this.logicalDeleteValue);
sb.append("'");
} else {
sb.append(this.logicalDeleteValue);
}
sb.append(XmlElementGeneratorTools.generateLogicalDeleteColumnValue(this.logicalDeleteColumn, this.logicalDeleteValue));
logicalDeleteByExample.addElement(new TextElement(sb.toString()));
logicalDeleteByExample.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
document.getRootElement().addElement(logicalDeleteByExample);
logger.debug("itfsw(逻辑删除插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加方法logicalDeleteByExample的实现。");
// hook
PluginTools.getHook(ILogicalDeletePluginHook.class).sqlMapLogicalDeleteByExampleElementGenerated(document, logicalDeleteByExample, this.logicalDeleteColumn, this.logicalDeleteValue, introspectedTable);
// 2. 判断是否有主键,生成主键删除方法
if (introspectedTable.hasPrimaryKeyColumns()) {
@@ -320,23 +306,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// 更新逻辑删除字段
sb1.append(this.logicalDeleteColumn.getActualColumnName());
sb1.append(" = ");
// 判断字段类型
JDBCType type1 = JDBCType.valueOf(this.logicalDeleteColumn.getJdbcType());
if (this.logicalDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalDeleteValue)) {
sb1.append("NULL");
} else if (JDBCType.CHAR == type1
|| JDBCType.LONGNVARCHAR == type1
|| JDBCType.LONGVARCHAR == type1
|| JDBCType.NCHAR == type1
|| JDBCType.NVARCHAR == type1
|| JDBCType.VARCHAR == type1) {
sb1.append("'");
sb1.append(this.logicalDeleteValue);
sb1.append("'");
} else {
sb1.append(this.logicalDeleteValue);
}
sb1.append(XmlElementGeneratorTools.generateLogicalDeleteColumnValue(this.logicalDeleteColumn, this.logicalDeleteValue));
logicalDeleteByPrimaryKey.addElement(new TextElement(sb1.toString()));
@@ -344,6 +314,8 @@ public class LogicalDeletePlugin extends BasePlugin {
document.getRootElement().addElement(logicalDeleteByPrimaryKey);
logger.debug("itfsw(逻辑删除插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加方法logicalDeleteByPrimaryKey的实现。");
// hook
PluginTools.getHook(ILogicalDeletePluginHook.class).sqlMapLogicalDeleteByPrimaryKeyElementGenerated(document, logicalDeleteByPrimaryKey, this.logicalDeleteColumn, this.logicalDeleteValue, introspectedTable);
// 3. 增强selectByPrimaryKey
@@ -393,10 +365,10 @@ public class LogicalDeletePlugin extends BasePlugin {
XmlElement chooseEle = new XmlElement("choose");
XmlElement whenEle = new XmlElement("when");
whenEle.addAttribute(new Attribute("test", PARAMETER_LOGICAL_DELETED));
whenEle.addElement(new TextElement("'" + this.logicalDeleteValue + "'"));
whenEle.addElement(new TextElement(XmlElementGeneratorTools.generateLogicalDeleteColumnValue(this.logicalDeleteColumn, this.logicalDeleteValue)));
chooseEle.addElement(whenEle);
XmlElement otherwiseEle = new XmlElement("otherwise");
otherwiseEle.addElement(new TextElement("'" + this.logicalUnDeleteValue + "'"));
otherwiseEle.addElement(new TextElement(XmlElementGeneratorTools.generateLogicalDeleteColumnValue(this.logicalDeleteColumn, this.logicalUnDeleteValue)));
chooseEle.addElement(otherwiseEle);
selectByPrimaryKey.addElement(chooseEle);
@@ -0,0 +1,256 @@
/*
* 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.IntrospectedTableTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.hook.ILombokPluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.List;
import java.util.Properties;
/**
* ---------------------------------------------------------------------------
* LombokPlugin
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/10/29 14:33
* ---------------------------------------------------------------------------
*/
public class LombokPlugin extends BasePlugin {
public static final String PRO_BUILDER = "@Builder"; // 是否支持 Builder 注解
public static final String PRO_ALL_ARGS_CONSTRUCTOR = "@AllArgsConstructor"; // 是否支持 AllArgsConstructor 注解
public static final String PRO_NO_ARGS_CONSTRUCTOR = "@NoArgsConstructor"; // 是否支持 NoArgsConstructor 注解
private boolean hasBuilder;
private boolean hasAllArgsConstructor;
private boolean hasNoArgsConstructor;
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param warnings
* @return
*/
@Override
public boolean validate(List<String> warnings) {
Properties properties = this.getProperties();
String builder = properties.getProperty(PRO_BUILDER);
String allArgsConstructor = properties.getProperty(PRO_ALL_ARGS_CONSTRUCTOR);
String noArgsConstructor = properties.getProperty(PRO_NO_ARGS_CONSTRUCTOR);
this.hasBuilder = builder == null ? false : StringUtility.isTrue(builder);
this.hasAllArgsConstructor = allArgsConstructor == null ? false : StringUtility.isTrue(allArgsConstructor);
this.hasNoArgsConstructor = noArgsConstructor == null ? false : StringUtility.isTrue(noArgsConstructor);
return super.validate(warnings);
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// @Data
this.addAnnotations(topLevelClass, EnumLombokAnnotations.DATA);
if (topLevelClass.getSuperClass() != null) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER);
this.addAnnotations(topLevelClass, EnumLombokAnnotations.TO_STRING_CALL_SUPER);
}
// @Builder
List<IntrospectedColumn> columns = IntrospectedTableTools.getModelBaseRecordClomns(introspectedTable);
if (this.hasBuilder && PluginTools.getHook(ILombokPluginHook.class).modelBaseRecordBuilderClassGenerated(topLevelClass, columns, introspectedTable)) {
// 有子类或者父类
if (introspectedTable.getRules().generateRecordWithBLOBsClass() || introspectedTable.getRules().generatePrimaryKeyClass() || topLevelClass.getSuperClass() != null) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.SUPER_BUILDER);
} else {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.BUILDER);
}
}
// @Constructor
if (this.hasNoArgsConstructor) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR);
}
if (this.hasAllArgsConstructor) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR);
}
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// @Data
this.addAnnotations(topLevelClass, EnumLombokAnnotations.DATA);
if (topLevelClass.getSuperClass() != null) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER);
this.addAnnotations(topLevelClass, EnumLombokAnnotations.TO_STRING_CALL_SUPER);
}
// @Builder
List<IntrospectedColumn> columns = introspectedTable.getPrimaryKeyColumns();
if (this.hasBuilder && PluginTools.getHook(ILombokPluginHook.class).modelPrimaryKeyBuilderClassGenerated(topLevelClass, columns, introspectedTable)) {
// 有子类或者父类
if (introspectedTable.getRules().generateRecordWithBLOBsClass() || introspectedTable.getRules().generateBaseRecordClass() || topLevelClass.getSuperClass() != null) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.SUPER_BUILDER);
} else {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.BUILDER);
}
}
// @Constructor
if (this.hasNoArgsConstructor) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR);
}
if (this.hasAllArgsConstructor) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR);
}
return super.modelPrimaryKeyClassGenerated(topLevelClass, introspectedTable);
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// @Data
this.addAnnotations(topLevelClass, EnumLombokAnnotations.DATA);
if (topLevelClass.getSuperClass() != null) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER);
this.addAnnotations(topLevelClass, EnumLombokAnnotations.TO_STRING_CALL_SUPER);
}
// @Builder
List<IntrospectedColumn> columns = introspectedTable.getBLOBColumns();
if (this.hasBuilder && PluginTools.getHook(ILombokPluginHook.class).modelRecordWithBLOBsBuilderClassGenerated(topLevelClass, columns, introspectedTable)) {
// 有子类或者父类
if (introspectedTable.getRules().generateBaseRecordClass() || introspectedTable.getRules().generatePrimaryKeyClass() || topLevelClass.getSuperClass() != null) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.SUPER_BUILDER);
} else {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.BUILDER);
}
}
// @Constructor
if (this.hasNoArgsConstructor) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR);
}
if (this.hasAllArgsConstructor) {
this.addAnnotations(topLevelClass, EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR);
}
return super.modelRecordWithBLOBsClassGenerated(topLevelClass, introspectedTable);
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param method
* @param topLevelClass
* @param introspectedColumn
* @param introspectedTable
* @param modelClassType
* @return
*/
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
return false;
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param method
* @param topLevelClass
* @param introspectedColumn
* @param introspectedTable
* @param modelClassType
* @return
*/
@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
return false;
}
/**
* 添加注解
* @param topLevelClass
* @param annotations
*/
private void addAnnotations(TopLevelClass topLevelClass, EnumLombokAnnotations annotations) {
topLevelClass.addImportedType(annotations.getClazz());
topLevelClass.addAnnotation(annotations.getAnnotation());
}
/**
* lombok 类型
*/
public enum EnumLombokAnnotations {
DATA("@Data", "lombok.Data"),
BUILDER("@Builder", "lombok.Builder"),
SUPER_BUILDER("@SuperBuilder", "lombok.experimental.SuperBuilder"),
ALL_ARGS_CONSTRUCTOR("@AllArgsConstructor", "lombok.AllArgsConstructor"),
NO_ARGS_CONSTRUCTOR("@NoArgsConstructor", "lombok.NoArgsConstructor"),
EQUALS_AND_HASH_CODE_CALL_SUPER("@EqualsAndHashCode(callSuper = true)", "lombok.EqualsAndHashCode"),
SETTER("@Setter", "lombok.Setter"),
ACCESSORS_FLUENT_TRUE("@Accessors(fluent = true)", "lombok.experimental.Accessors"),
TO_STRING("@ToString", "lombok.ToString"),
TO_STRING_CALL_SUPER("@ToString(callSuper = true)", "lombok.ToString");
private final String annotation;
private final String clazz;
EnumLombokAnnotations(String annotation, String clazz) {
this.annotation = annotation;
this.clazz = clazz;
}
/**
* Getter method for property <tt>annotation</tt>.
* @return property value of annotation
* @author hewei
*/
public String getAnnotation() {
return annotation;
}
/**
* Getter method for property <tt>clazz</tt>.
* @return property value of clazz
* @author hewei
*/
public String getClazz() {
return clazz;
}
}
}
@@ -17,6 +17,7 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.ILogicalDeletePluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IModelBuilderPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IOptimisticLockerPluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
@@ -38,9 +39,11 @@ import java.util.*;
* @time:2018/4/26 10:24
* ---------------------------------------------------------------------------
*/
public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderPluginHook {
public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderPluginHook, ILogicalDeletePluginHook {
public static final String METHOD_DELETE_WITH_VERSION_BY_EXAMPLE = "deleteWithVersionByExample"; // 方法名
public static final String METHOD_DELETE_WITH_VERSION_BY_PRIMARY_KEY = "deleteWithVersionByPrimaryKey"; // 方法名
public static final String METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE = "logicalDeleteWithVersionByExample"; // 方法名
public static final String METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY = "logicalDeleteWithVersionByPrimaryKey"; // 方法名
public static final String METHOD_UPDATE_WITH_VERSION_BY_EXAMPLE_SELECTIVE = "updateWithVersionByExampleSelective"; // 方法名
public static final String METHOD_UPDATE_WITH_VERSION_BY_EXAMPLE_WITH_BLOBS = "updateWithVersionByExampleWithBLOBs"; // 方法名
public static final String METHOD_UPDATE_WITH_VERSION_BY_EXAMPLE_WITHOUT_BLOBS = "updateWithVersionByExample"; // 方法名
@@ -113,6 +116,54 @@ public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderP
return super.clientDeleteByPrimaryKeyMethodGenerated(method, interfaze, introspectedTable);
}
@Override
public boolean clientLogicalDeleteByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
if (this.versionColumn != null) {
if (this.customizedNextVersion) {
Method newMethod = JavaElementGeneratorTools.generateMethod(
METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(this.versionColumn.getFullyQualifiedJavaType(), "version", "@Param(\"version\")"),
new Parameter(this.versionColumn.getFullyQualifiedJavaType(), "nextVersion", "@Param(\"nextVersion\")"),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")")
);
commentGenerator.addGeneralMethodComment(newMethod, introspectedTable);
FormatTools.addMethodWithBestPosition(interfaze, newMethod);
} else {
FormatTools.addMethodWithBestPosition(
interfaze,
this.replaceDeleteExampleMethod(introspectedTable, method, interfaze, METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE)
);
}
}
return true;
}
@Override
public boolean clientLogicalDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
if (this.versionColumn != null) {
if (this.customizedNextVersion) {
Method newMethod = JavaElementGeneratorTools.generateMethod(
METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(this.versionColumn.getFullyQualifiedJavaType(), "version", "@Param(\"version\")"),
new Parameter(this.versionColumn.getFullyQualifiedJavaType(), "nextVersion", "@Param(\"nextVersion\")"),
new Parameter(method.getParameters().get(0).getType(), method.getParameters().get(0).getName(), "@Param(\"key\")")
);
commentGenerator.addGeneralMethodComment(newMethod, introspectedTable);
FormatTools.addMethodWithBestPosition(interfaze, newMethod);
} else {
FormatTools.addMethodWithBestPosition(
interfaze,
this.replaceDeletePrimaryKeyMethod(introspectedTable, method, interfaze, METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY)
);
}
}
return true;
}
@Override
public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
if (this.versionColumn != null) {
@@ -420,6 +471,33 @@ public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderP
return super.sqlMapExampleWhereClauseElementGenerated(element, introspectedTable);
}
@Override
public boolean sqlMapLogicalDeleteByExampleElementGenerated(Document document, XmlElement element, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, IntrospectedTable introspectedTable) {
if (this.versionColumn != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.generateSqlMapLogicalDelete(
introspectedTable,
METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE,
logicalDeleteColumn,
logicalDeleteValue,
true
));
}
return true;
}
@Override
public boolean sqlMapLogicalDeleteByPrimaryKeyElementGenerated(Document document, XmlElement element, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, IntrospectedTable introspectedTable) {
if (this.versionColumn != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.generateSqlMapLogicalDelete(
introspectedTable,
METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY,
logicalDeleteColumn,
logicalDeleteValue,
false
));
}
return true;
}
// =================================================== 一些生成方法 ========================================
@@ -529,7 +607,7 @@ public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderP
FormatTools.replaceGeneralMethodComment(commentGenerator, withVersionMethod, introspectedTable);
Parameter versionParam = new Parameter(this.versionColumn.getFullyQualifiedJavaType(), "version", "@Param(\"version\")");
Parameter keyParam = new Parameter(method.getParameters().get(0).getType(), "key", "@Param(\"key\")");
Parameter keyParam = new Parameter(method.getParameters().get(0).getType(), method.getParameters().get(0).getName(), "@Param(\"key\")");
withVersionMethod.getParameters().clear();
withVersionMethod.addParameter(versionParam);
@@ -702,6 +780,67 @@ public class OptimisticLockerPlugin extends BasePlugin implements IModelBuilderP
return updateEle;
}
/**
* 生成LogicalDelete sql map
* @param introspectedTable
* @param id
* @param logicalDeleteColumn
* @param logicalDeleteValue
* @param byExample
* @return
*/
private XmlElement generateSqlMapLogicalDelete(IntrospectedTable introspectedTable, String id, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, boolean byExample) {
XmlElement updateEle = new XmlElement("update");
updateEle.addAttribute(new Attribute("id", id));
updateEle.addAttribute(new Attribute("parameterType", "map"));
commentGenerator.addComment(updateEle);
updateEle.addElement(new TextElement("update " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
StringBuilder sb = new StringBuilder("set ");
// 版本自增
if (this.customizedNextVersion) {
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(this.versionColumn));
sb.append(" = ");
sb.append("#{nextVersion,jdbcType=");
sb.append(this.versionColumn.getJdbcTypeName());
if (StringUtility.stringHasValue(this.versionColumn.getTypeHandler())) {
sb.append(",typeHandler=");
sb.append(this.versionColumn.getTypeHandler());
}
sb.append("}");
} else {
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(this.versionColumn));
sb.append(" = ");
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(this.versionColumn));
sb.append(" + 1");
}
sb.append(",");
// 逻辑删除 set
sb.append(logicalDeleteColumn.getActualColumnName());
sb.append(" = ");
sb.append(XmlElementGeneratorTools.generateLogicalDeleteColumnValue(logicalDeleteColumn, logicalDeleteValue));
updateEle.addElement(new TextElement(sb.toString()));
// 更新条件
if (byExample) {
XmlElement ifElement = new XmlElement("if");
ifElement.addAttribute(new Attribute("test", "_parameter != null"));
XmlElement includeElement = new XmlElement("include");
includeElement.addAttribute(new Attribute("refid", SQL_UPDATE_BY_EXAMPLE_WITH_VERSION_WHERE_CLAUSE));
ifElement.addElement(includeElement);
updateEle.addElement(ifElement);
} else {
updateEle = this.replacePrimaryKeyXmlElement(introspectedTable, updateEle, id, false);
}
return updateEle;
}
/**
* 生成版本号set节点
* @param selective
@@ -1,116 +0,0 @@
/*
* Copyright (c) 2017.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.IncrementsPlugin;
import com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 增量插件工具
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/21 16:12
* ---------------------------------------------------------------------------
*/
public class IncrementsPluginTools {
private IntrospectedTable introspectedTable; // 表
private List<IntrospectedColumn> columns = new ArrayList<>(); // 表启用增量操作的字段
/**
* 构造函数
* @param introspectedTable
*/
private IncrementsPluginTools(IntrospectedTable introspectedTable) {
this.introspectedTable = introspectedTable;
}
/**
* 获取工具
* @param context
* @param introspectedTable
* @param warnings
* @return
*/
public static IncrementsPluginTools getTools(Context context, IntrospectedTable introspectedTable, List<String> warnings) {
IncrementsPluginTools tools = new IncrementsPluginTools(introspectedTable);
// 判断是否启用了插件
if (PluginTools.getPluginConfiguration(context, IncrementsPlugin.class) != null) {
String incrementsColumns = introspectedTable.getTableConfigurationProperty(IncrementsPlugin.PRO_INCREMENTS_COLUMNS);
if (StringUtility.stringHasValue(incrementsColumns)) {
// 切分
String[] incrementsColumnsStrs = incrementsColumns.split(",");
for (String incrementsColumnsStr : incrementsColumnsStrs) {
IntrospectedColumn column = IntrospectedTableTools.safeGetColumn(introspectedTable, incrementsColumnsStr);
if (column == null) {
warnings.add("itfsw:插件" + IncrementsPlugin.class.getTypeName() + "插件没有找到column为" + incrementsColumnsStr.trim() + "的字段!");
} else {
tools.columns.add(column);
}
}
}
}
return tools;
}
/**
* 获取INC Enum
* @return
*/
public FullyQualifiedJavaType getIncEnum() {
return new FullyQualifiedJavaType(this.introspectedTable.getFullyQualifiedTable().getDomainObjectName() + "." + ModelBuilderPlugin.BUILDER_CLASS_NAME + ".Inc");
}
/**
* 是否启用了
* @return
*/
public boolean support() {
return this.columns.size() > 0;
}
/**
* Getter method for property <tt>columns</tt>.
* @return property value of columns
* @author hewei
*/
public List<IntrospectedColumn> getColumns() {
return columns;
}
/**
* 判断是否为需要进行增量操作的column
* @param searchColumn
* @return
*/
public boolean supportColumn(IntrospectedColumn searchColumn) {
for (IntrospectedColumn column : this.columns) {
if (column.getActualColumnName().equals(searchColumn.getActualColumnName())) {
return true;
}
}
return false;
}
}
@@ -28,12 +28,12 @@ import org.mybatis.generator.internal.util.StringUtility;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* IntrospectedTable 的一些拓展增强
* ---------------------------------------------------------------------------
*
* @author: hewei
* @time:2017/6/13 13:48
* ---------------------------------------------------------------------------
@@ -42,7 +42,6 @@ public class IntrospectedTableTools {
/**
* 设置DomainObjectName和MapperName
*
* @param introspectedTable
* @param context
* @param domainObjectName
@@ -84,7 +83,6 @@ public class IntrospectedTableTools {
/**
* 安全获取column 通过正则获取的name可能包含beginningDelimiter&&endingDelimiter
*
* @param introspectedTable
* @param columnName
* @return
@@ -104,4 +102,49 @@ public class IntrospectedTableTools {
return introspectedTable.getColumn(columnName);
}
/**
* 获取生成model baseRecord的列
* @param introspectedTable
* @return
*/
public static List<IntrospectedColumn> getModelBaseRecordClomns(IntrospectedTable introspectedTable) {
List<IntrospectedColumn> introspectedColumns;
if (includePrimaryKeyColumns(introspectedTable)) {
if (includeBLOBColumns(introspectedTable)) {
introspectedColumns = introspectedTable.getAllColumns();
} else {
introspectedColumns = introspectedTable.getNonBLOBColumns();
}
} else {
if (includeBLOBColumns(introspectedTable)) {
introspectedColumns = introspectedTable
.getNonPrimaryKeyColumns();
} else {
introspectedColumns = introspectedTable.getBaseColumns();
}
}
return introspectedColumns;
}
/**
* 是否有primaryKey 列
* @param introspectedTable
* @return
*/
public static boolean includePrimaryKeyColumns(IntrospectedTable introspectedTable) {
return !introspectedTable.getRules().generatePrimaryKeyClass()
&& introspectedTable.hasPrimaryKeyColumns();
}
/**
* 是否有 blob 列
* @param introspectedTable
* @return
*/
public static boolean includeBLOBColumns(IntrospectedTable introspectedTable) {
return !introspectedTable.getRules().generateRecordWithBLOBsClass()
&& introspectedTable.hasBLOBColumns();
}
}
@@ -49,11 +49,16 @@ public class PluginTools {
/**
* 检查插件依赖
* @param context 上下文
* @param plugin 插件
* @param plugins 插件
* @return
*/
public static boolean checkDependencyPlugin(Context context, Class plugin) {
return getPluginIndex(context, plugin) >= 0;
public static boolean checkDependencyPlugin(Context context, Class... plugins) {
for (Class plugin : plugins) {
if (getPluginIndex(context, plugin) < 0) {
return false;
}
}
return true;
}
/**
@@ -557,4 +557,29 @@ public class XmlElementGeneratorTools {
}
return resultElement;
}
/**
* 生成逻辑删除列的删除值
* @param logicalDeleteColumn
* @param value
* @return
*/
public static String generateLogicalDeleteColumnValue(IntrospectedColumn logicalDeleteColumn, String value) {
StringBuilder sb = new StringBuilder();
// 判断字段类型
if (value == null || "NULL".equalsIgnoreCase(value)) {
sb.append("NULL");
} else if (logicalDeleteColumn.isStringColumn()) {
sb.append("'");
sb.append(value);
sb.append("'");
} else if (logicalDeleteColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Long.class.getName())){
sb.append(value.replaceAll("L|l", ""));
} else if (logicalDeleteColumn.getFullyQualifiedJavaType().getFullyQualifiedName().equals(Float.class.getName())){
sb.append(value.replaceAll("F|f", ""));
} else {
sb.append(value);
}
return sb.toString();
}
}
@@ -0,0 +1,45 @@
/*
* 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.enhanced;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/11/2 18:21
* ---------------------------------------------------------------------------
*/
public class SpecTypeArgumentsFullyQualifiedJavaType extends FullyQualifiedJavaType {
private String fullTypeSpecification;
/**
* Use this constructor to construct a generic type with the specified type parameters.
* @param fullTypeSpecification the full type specification
*/
public SpecTypeArgumentsFullyQualifiedJavaType(String fullTypeSpecification) {
super("");
this.fullTypeSpecification = fullTypeSpecification;
}
@Override
public String getShortName() {
return this.fullTypeSpecification.substring(1, this.fullTypeSpecification.length() - 1);
}
}
@@ -43,7 +43,15 @@ import java.util.List;
* @time:2018/4/27 11:33
* ---------------------------------------------------------------------------
*/
public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHook, IIncrementsPluginHook, IOptimisticLockerPluginHook, ISelectOneByExamplePluginHook, ITableConfigurationHook {
public class HookAggregator implements IUpsertPluginHook,
IModelBuilderPluginHook,
IIncrementsPluginHook,
IOptimisticLockerPluginHook,
ISelectOneByExamplePluginHook,
ITableConfigurationHook,
ILombokPluginHook,
ILogicalDeletePluginHook {
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class); // 日志
private final static HookAggregator instance = new HookAggregator();
private Context context;
@@ -256,7 +264,83 @@ public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHoo
@Override
public void tableConfiguration(IntrospectedTable introspectedTable) {
if (!this.getPlugins(ITableConfigurationHook.class).isEmpty()) {
this.getPlugins(ITableConfigurationHook.class).get(0).tableConfiguration(introspectedTable);
this.getPlugins(ITableConfigurationHook.class).get(0).tableConfiguration(introspectedTable);
}
}
// ============================================= ILogicalDeletePluginHook ==============================================
@Override
public boolean clientLogicalDeleteByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (ILogicalDeletePluginHook plugin : this.getPlugins(ILogicalDeletePluginHook.class)) {
if (!plugin.clientLogicalDeleteByExampleMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean clientLogicalDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (ILogicalDeletePluginHook plugin : this.getPlugins(ILogicalDeletePluginHook.class)) {
if (!plugin.clientLogicalDeleteByPrimaryKeyMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean sqlMapLogicalDeleteByExampleElementGenerated(Document document, XmlElement element, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, IntrospectedTable introspectedTable) {
for (ILogicalDeletePluginHook plugin : this.getPlugins(ILogicalDeletePluginHook.class)) {
if (!plugin.sqlMapLogicalDeleteByExampleElementGenerated(document, element, logicalDeleteColumn, logicalDeleteValue, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean sqlMapLogicalDeleteByPrimaryKeyElementGenerated(Document document, XmlElement element, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, IntrospectedTable introspectedTable) {
for (ILogicalDeletePluginHook plugin : this.getPlugins(ILogicalDeletePluginHook.class)) {
if (!plugin.sqlMapLogicalDeleteByPrimaryKeyElementGenerated(document, element, logicalDeleteColumn, logicalDeleteValue, introspectedTable)) {
return false;
}
}
return true;
}
// ============================================= ILombokPluginHook ==============================================
@Override
public boolean modelBaseRecordBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
for (ILombokPluginHook plugin : this.getPlugins(ILombokPluginHook.class)) {
if (!plugin.modelBaseRecordBuilderClassGenerated(topLevelClass, columns, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean modelPrimaryKeyBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
for (ILombokPluginHook plugin : this.getPlugins(ILombokPluginHook.class)) {
if (!plugin.modelPrimaryKeyBuilderClassGenerated(topLevelClass, columns, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean modelRecordWithBLOBsBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable) {
for (ILombokPluginHook plugin : this.getPlugins(ILombokPluginHook.class)) {
if (!plugin.modelRecordWithBLOBsBuilderClassGenerated(topLevelClass, columns, introspectedTable)) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,74 @@
/*
* 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.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/9/11 11:00
* ---------------------------------------------------------------------------
*/
public interface ILogicalDeletePluginHook {
/**
* logicalDeleteByExample
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
boolean clientLogicalDeleteByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable);
/**
* logicalDeleteByPrimaryKey
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
boolean clientLogicalDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable);
/**
* logicalDeleteByExample
* @param document
* @param element
* @param logicalDeleteColumn
* @param logicalDeleteValue
* @param introspectedTable
* @return
*/
boolean sqlMapLogicalDeleteByExampleElementGenerated(Document document, XmlElement element, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, IntrospectedTable introspectedTable);
/**
* logicalDeleteByPrimaryKey
* @param document
* @param element
* @param logicalDeleteColumn
* @param logicalDeleteValue
* @param introspectedTable
* @return
*/
boolean sqlMapLogicalDeleteByPrimaryKeyElementGenerated(Document document, XmlElement element, IntrospectedColumn logicalDeleteColumn, String logicalDeleteValue, IntrospectedTable introspectedTable);
}
@@ -0,0 +1,60 @@
/*
* 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.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/10/31 17:27
* ---------------------------------------------------------------------------
*/
public interface ILombokPluginHook {
/**
* Model builder class 生成
* @param topLevelClass
* @param columns
* @param introspectedTable
* @return
*/
boolean modelBaseRecordBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable);
/**
* Model builder class 生成
* @param topLevelClass
* @param columns
* @param introspectedTable
* @return
*/
boolean modelPrimaryKeyBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable);
/**
* Model builder class 生成
* @param topLevelClass
* @param columns
* @param introspectedTable
* @return
*/
boolean modelRecordWithBLOBsBuilderClassGenerated(TopLevelClass topLevelClass, List<IntrospectedColumn> columns, IntrospectedTable introspectedTable);
}
@@ -88,6 +88,27 @@ public class ExampleEnhancedPluginTest {
});
}
/**
* 测试静态 createCriteria
* @throws Exception
*/
@Test
public void testStaticCreateCriteria() throws Exception{
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ExampleEnhancedPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
ObjectUtil tbExampleCriteria = new ObjectUtil(loader.loadClass(packagz + ".TbExample").getMethod(ExampleEnhancedPlugin.METHOD_NEW_AND_CREATE_CRITERIA).invoke(null));
// 调用example方法能正常返回
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbExampleCriteria.invoke("example"));
Assert.assertEquals(sql, "select id, field1, field2 from tb");
}
});
}
/**
* 测试andIf方法
*/
@@ -54,7 +54,7 @@ public class IncrementsPluginTest {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-without-model-builder-plugin.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.IncrementsPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin插件使用!");
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.IncrementsPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin或者com.itfsw.mybatis.generator.plugins.LombokPlugin插件使用!");
}
/**
@@ -63,7 +63,7 @@ public class IncrementsPluginTest {
@Test
public void testModelBuilderMethod() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator.xml");
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试生成的方法
@@ -112,7 +112,7 @@ public class IncrementsPluginTest {
@Test
public void testSqlAndExecute() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator.xml");
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
@@ -154,7 +154,7 @@ public class IncrementsPluginTest {
// 2. 测试updateByPrimaryKey、updateByPrimaryKeySelective
ObjectUtil tbKeysMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbKeysMapper")));
ObjectUtil tbKeysBuilderInc = new ObjectUtil(loader, packagz + ".TbKeys$Builder$Inc#INC");
ObjectUtil tbKeysBuilderInc = new ObjectUtil(loader, packagz + ".TbKeysKey$Builder$Inc#INC");
ObjectUtil tbKeysBuilder = new ObjectUtil(loader, packagz + ".TbKeys$Builder");
tbKeysBuilder.invoke("key1", 1l);
@@ -214,7 +214,7 @@ public class IncrementsPluginTest {
@Test
public void testWithSelectiveEnhancedPlugin() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-selective-enhanced-plugin.xml");
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试updateByExampleSelective
@@ -268,7 +268,7 @@ public class IncrementsPluginTest {
// 2. 测试updateByPrimaryKeySelective
ObjectUtil tbKeysMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbKeysMapper")));
ObjectUtil tbKeysBuilderInc = new ObjectUtil(loader, packagz + ".TbKeys$Builder$Inc#INC");
ObjectUtil tbKeysBuilderInc = new ObjectUtil(loader, packagz + ".TbKeysKey$Builder$Inc#INC");
ObjectUtil tbKeysBuilder = new ObjectUtil(loader, packagz + ".TbKeys$Builder");
tbKeysBuilder.invoke("key1", 1l);
@@ -307,7 +307,7 @@ public class IncrementsPluginTest {
@Test
public void testWithUpsertPlugin() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-upsert-plugin.xml");
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/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")));
@@ -399,7 +399,7 @@ public class IncrementsPluginTest {
@Test
public void testWithAutoDelimitKeywords() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-autoDelimitKeywords.xml");
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试updateByExample、updateByExampleSelective
@@ -433,7 +433,7 @@ public class IncrementsPluginTest {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-upsert-and-selective-enhanced-plugin.xml");
// upsertSelective 基于原生非空判断
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/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")));
@@ -459,7 +459,7 @@ public class IncrementsPluginTest {
});
// upsertByExampleSelective 基于原生非空判断
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试updateByExampleSelective
@@ -499,7 +499,7 @@ public class IncrementsPluginTest {
});
// upsertSelective 基于指定字段
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/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")));
@@ -536,7 +536,7 @@ public class IncrementsPluginTest {
});
// upsertByExampleSelective 基于指定字段
tool.generate(() -> DBHelper.resetDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试updateByExampleSelective
@@ -585,4 +585,87 @@ public class IncrementsPluginTest {
}
});
}
/**
* 测试同时整合 LombokPlugin
*/
@Test
public void testWithLombokPlugin() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-with-LombokPlugin.xml");
tool.generate(() -> DBHelper.createDB("scripts/IncrementsPlugin/init-lombok.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// ------------------------------------- builder ----------------------------------------
// normal builder
ObjectUtil tbBuilder = new ObjectUtil(loader.loadClass(packagz + ".Tb").getMethod("builder").invoke(null));
tbBuilder = new ObjectUtil(tbBuilder.invoke("id", 1L));
tbBuilder.invoke("field1", "ts1");
ObjectUtil tb = new ObjectUtil(tbBuilder.invoke("build"));
Assert.assertEquals(tb.invoke("toString"), "Tb(id=1, field1=ts1, field2=null, incrementsColumnsInfoMap={})");
// super
ObjectUtil tbLombokWithBLOBsBuilder = new ObjectUtil(loader.loadClass(packagz + ".TbLombokWithBLOBs").getMethod("builder").invoke(null));
tbLombokWithBLOBsBuilder.invoke("field3", "ts3");
Assert.assertEquals(tbLombokWithBLOBsBuilder.invoke("toString"), "TbLombokWithBLOBs.TbLombokWithBLOBsBuilder(super=TbLombok.TbLombokBuilder(super=TbLombokKey.TbLombokKeyBuilder(id=null, key1=null, incrementsColumnsInfoMap={}), field1=null, incF1=null), field3=ts3, field4=null)");
tbLombokWithBLOBsBuilder.invoke("field1", "ts1");
Assert.assertEquals(tbLombokWithBLOBsBuilder.invoke("toString"), "TbLombokWithBLOBs.TbLombokWithBLOBsBuilder(super=TbLombok.TbLombokBuilder(super=TbLombokKey.TbLombokKeyBuilder(id=null, key1=null, incrementsColumnsInfoMap={}), field1=ts1, incF1=null), field3=ts3, field4=null)");
tbLombokWithBLOBsBuilder.invoke("id", 100L);
Assert.assertEquals(tbLombokWithBLOBsBuilder.invoke("toString"), "TbLombokWithBLOBs.TbLombokWithBLOBsBuilder(super=TbLombok.TbLombokBuilder(super=TbLombokKey.TbLombokKeyBuilder(id=100, key1=null, incrementsColumnsInfoMap={}), field1=ts1, incF1=null), field3=ts3, field4=null)");
// ------------------------------------- 测试 sql 执行 ----------------------------------------
// 1. 测试updateByExample、updateByExampleSelective
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", 3l);
tbBuilder = new ObjectUtil(loader.loadClass(packagz + ".Tb").getMethod("builder").invoke(null));
ObjectUtil tbBuilderInc = new ObjectUtil(loader, packagz + ".Tb$TbBuilder$Inc#INC");
tbBuilder.invoke("field2", 100, tbBuilderInc.getObject());
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExample", tbBuilder.invoke("build"), tbExample.getObject());
Assert.assertEquals(sql, "update tb set id = null, field1 = 'null', field2 = field2 + 100 WHERE ( id = '3' )");
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject());
Assert.assertEquals(sql, "update tb SET field2 = field2 + 100 WHERE ( id = '3' )");
// 执行
// inc_f1 增加100
Object result = tbMapper.invoke("updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject());
Assert.assertEquals(result, 1);
ResultSet rs = DBHelper.execute(sqlSession.getConnection(), "select field2 from tb where id = 3");
rs.first();
Assert.assertEquals(rs.getInt("field2"), 103);
// 2. 测试有SuperBuilder的情况
ObjectUtil tbLombokMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbLombokMapper")));
ObjectUtil tbLombokExample = new ObjectUtil(loader, packagz + ".TbLombokExample");
criteria = new ObjectUtil(tbLombokExample.invoke("createCriteria"));
criteria.invoke("andKey1EqualTo", "key1");
tbLombokWithBLOBsBuilder = new ObjectUtil(loader.loadClass(packagz + ".TbLombokWithBLOBs").getMethod("builder").invoke(null));
tbLombokWithBLOBsBuilder.invoke("field3", "f3");
ObjectUtil tbLombokKeyBuilderIncINC = new ObjectUtil(loader, packagz + ".TbLombokKey$TbLombokKeyBuilder$Inc#INC");
tbLombokWithBLOBsBuilder.invoke("incF1", (short)1, tbLombokKeyBuilderIncINC.getObject());
tbLombokWithBLOBsBuilder.invoke("field1", "ts33");
ObjectUtil tbLombokKeyBuilderIncDEC = new ObjectUtil(loader, packagz + ".TbLombokKey$TbLombokKeyBuilder$Inc#DEC");
tbLombokWithBLOBsBuilder.invoke("id", 100L, tbLombokKeyBuilderIncDEC.getObject());
tbLombokWithBLOBsBuilder.invoke("key1", "key100");
// sql
sql = SqlHelper.getFormatMapperSql(tbLombokMapper.getObject(), "updateByExampleSelective", tbLombokWithBLOBsBuilder.invoke("build"), tbLombokExample.getObject());
Assert.assertEquals(sql, "update tb_lombok SET id = id - 100 , key1 = 'key100', field1 = 'ts33', inc_f1 = inc_f1 + 1 , field3 = 'f3' WHERE ( key1 = 'key1' )");
// 执行
result = tbLombokMapper.invoke("updateByExampleSelective", tbLombokWithBLOBsBuilder.invoke("build"), tbLombokExample.getObject());
Assert.assertEquals(result, 1);
rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb_lombok where key1 = 'key100'");
rs.first();
Assert.assertEquals(rs.getInt("inc_f1"), 1);
Assert.assertEquals(rs.getInt("id"), -99);
}
});
}
}
@@ -215,7 +215,7 @@ public class LogicalDeletePluginTest {
// 验证sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByPrimaryKeyWithLogicalDelete", 5l, true);
Assert.assertEquals(sql, "select id, del_flag, and_logical_deleted, ts_1, ts_3, ts_4 , ts_2 from tb where id = 5 and del_flag = '1'");
Assert.assertEquals(sql, "select id, del_flag, and_logical_deleted, ts_1, ts_3, ts_4 , ts_2 from tb where id = 5 and del_flag = 1");
// 验证执行
Object result = tbMapper.invoke("selectByPrimaryKeyWithLogicalDelete", 5l, true);
Assert.assertNull(result);
@@ -0,0 +1,316 @@
/*
* 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.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 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.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/10/29 15:45
* ---------------------------------------------------------------------------
*/
public class LombokPluginTest {
/**
* 初始化
*/
@BeforeClass
public static void init() throws Exception {
DBHelper.createDB("scripts/LombokPlugin/init.sql");
}
/**
* 测试具体生成
*/
@Test
public void testGenerate() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LombokPlugin/mybatis-generator.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
CompilationUnit compilationUnit = file.getCompilationUnit();
String name = compilationUnit.getType().getShortName();
if ("TbKeyBlobKey".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA,
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.BUILDER,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER
), false));
} else if ("TbKeyBlobWithBLOBs".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA,
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.BUILDER
), false));
}
// tb 没有继承
if ("Tb".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA,
LombokPlugin.EnumLombokAnnotations.BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER
), false));
}
if ("TbKeysKey".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA,
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.BUILDER,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER
), false));
} else if ("TbKeys".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA,
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.BUILDER
), false));
}
}
}
/**
* 测试具体生成
*/
@Test
public void testGenerateDefault() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LombokPlugin/mybatis-generator-default.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
CompilationUnit compilationUnit = file.getCompilationUnit();
String name = compilationUnit.getType().getShortName();
if ("TbKeyBlobKey".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.BUILDER,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER,
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR
), false));
} else if ("TbKeyBlobWithBLOBs".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.BUILDER,
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR
), false));
}
// tb 没有继承
if ("Tb".equals(name)) {
Assert.assertTrue(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.DATA
), true));
Assert.assertFalse(checkImportedType(compilationUnit.getImportedTypes(), Arrays.asList(
LombokPlugin.EnumLombokAnnotations.SUPER_BUILDER,
LombokPlugin.EnumLombokAnnotations.EQUALS_AND_HASH_CODE_CALL_SUPER,
LombokPlugin.EnumLombokAnnotations.BUILDER,
LombokPlugin.EnumLombokAnnotations.NO_ARGS_CONSTRUCTOR,
LombokPlugin.EnumLombokAnnotations.ALL_ARGS_CONSTRUCTOR
), false));
}
}
}
/**
* 测试 @Data 注解
* @throws Exception
*/
@Test
public void testDataAnnotation() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LombokPlugin/mybatis-generator-data.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// get & set
ObjectUtil tbLombok = new ObjectUtil(loader, packagz + ".TbLombok");
tbLombok.invoke("setField1", "ts1");
Assert.assertEquals(tbLombok.invoke("getField1"), "ts1");
// get & set with parent
tbLombok.invoke("setKey1", "ts2");
Assert.assertEquals(tbLombok.invoke("getKey1"), "ts2");
// get & set with Boolean
tbLombok.invoke("setIsFind", true);
Assert.assertEquals(tbLombok.invoke("getIsFind"), true);
// equals & hash & toString
ObjectUtil tbLombok1 = new ObjectUtil(loader, packagz + ".TbLombok");
tbLombok1.invoke("setField1", "ts1");
ObjectUtil tbLombok2 = new ObjectUtil(loader, packagz + ".TbLombok");
tbLombok2.invoke("setField1", "ts1");
Assert.assertEquals(tbLombok1.invoke("equals", tbLombok2.getObject()), true);
Assert.assertEquals(tbLombok1.invoke("hashCode"), tbLombok2.invoke("hashCode"));
Assert.assertEquals(tbLombok1.invoke("toString"), "TbLombok(super=TbLombokKey(id=null, key1=null), field1=ts1, isFind=null)");
// equals & hash & toString with parent
tbLombok1.invoke("setKey1", "ts2");
tbLombok2.invoke("setKey1", "ts2");
Assert.assertEquals(tbLombok1.invoke("equals", tbLombok2.getObject()), true);
Assert.assertEquals(tbLombok1.invoke("hashCode"), tbLombok2.invoke("hashCode"));
Assert.assertEquals(tbLombok1.invoke("toString"), "TbLombok(super=TbLombokKey(id=null, key1=ts2), field1=ts1, isFind=null)");
// @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true)
tbLombok1.invoke("setId", 1L);
Assert.assertEquals(tbLombok1.invoke("equals", tbLombok2.getObject()), false);
Assert.assertNotEquals(tbLombok1.invoke("hashCode"), tbLombok2.invoke("hashCode"));
Assert.assertEquals(tbLombok1.invoke("toString"), "TbLombok(super=TbLombokKey(id=1, key1=ts2), field1=ts1, isFind=null)");
}
});
}
/**
* 测试 @Builder 注解
* @throws Exception
*/
@Test
public void testBuilderAnnotation() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LombokPlugin/mybatis-generator-builder.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// normal builder
ObjectUtil tbBuilder = new ObjectUtil(loader.loadClass(packagz + ".Tb").getMethod("builder").invoke(null));
tbBuilder = new ObjectUtil(tbBuilder.invoke("id", 1L));
tbBuilder.invoke("field1", "ts1");
ObjectUtil tb = new ObjectUtil(tbBuilder.invoke("build"));
Assert.assertEquals(tb.invoke("toString"), "Tb(id=1, field1=ts1, field2=null)");
// super builder
ObjectUtil tbLombokBuilder = new ObjectUtil(loader.loadClass(packagz + ".TbLombok").getMethod("builder").invoke(null));
tbLombokBuilder.invoke("field1", "ts1");
Assert.assertEquals(tbLombokBuilder.invoke("toString"), "TbLombok.TbLombokBuilder(super=TbLombokKey.TbLombokKeyBuilder(id=null, key1=null), field1=ts1, isFind=null)");
tbLombokBuilder.invoke("id", 100L);
Assert.assertEquals(tbLombokBuilder.invoke("toString"), "TbLombok.TbLombokBuilder(super=TbLombokKey.TbLombokKeyBuilder(id=100, key1=null), field1=ts1, isFind=null)");
}
});
}
/**
* 测试 @NoArgsConstructor @AllArgsConstructor 注解
* @throws Exception
*/
@Test
public void testConstructorAnnotation() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LombokPlugin/mybatis-generator-constructor.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
Class clazz = loader.loadClass(packagz + ".TbLombok");
try {
// 无参
ObjectUtil tbLombok = new ObjectUtil(clazz.newInstance());
Assert.assertEquals(tbLombok.invoke("toString"), "TbLombok(super=TbLombokKey(id=null, key1=null), field1=null, isFind=null)");
// 有参
Constructor constructor = clazz.getConstructor(String.class, Boolean.class);
tbLombok = new ObjectUtil(constructor.newInstance("ts1", true));
Assert.assertEquals(tbLombok.invoke("toString"), "TbLombok(super=TbLombokKey(id=null, key1=null), field1=ts1, isFind=true)");
} catch (Exception e) {
Assert.assertTrue(false);
}
}
});
}
/**
* 验证引包
* @param importedTypes
* @param annotations
* @param all
* @return
*/
private boolean checkImportedType(Set<FullyQualifiedJavaType> importedTypes, List<LombokPlugin.EnumLombokAnnotations> annotations, boolean all) {
for (LombokPlugin.EnumLombokAnnotations annotation : annotations) {
boolean find = false;
for (FullyQualifiedJavaType javaType : importedTypes) {
if (javaType.getFullyQualifiedName().equals(annotation.getClazz())) {
if (all) {
find = true;
} else {
return true;
}
}
}
if (find == false) {
return false;
}
}
return true;
}
}
@@ -334,6 +334,102 @@ public class OptimisticLockerPluginTest {
});
}
/**
* 测试整合LogicalDelete插件
*/
@Test
public void testWithLogicalDeletePlugin() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OptimisticLockerPlugin/mybatis-generator-with-LogicalDeletePlugin.xml");
tool.generate(() -> DBHelper.resetDB("scripts/OptimisticLockerPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// ---------------------------------------- logicalDeleteWithVersionByExample ---------------------------------------
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);
// 验证sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE, 0L, tbExample.getObject());
Assert.assertEquals(sql, "update tb set inc_f1 = inc_f1 + 1,inc_f2 = 9 WHERE inc_f1 = 0 and ( ( id = '1' ) )");
// 验证执行
Object result = tbMapper.invoke(OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE, 0L, tbExample.getObject());
Assert.assertEquals(result, 1);
ResultSet rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb where id = 1");
rs.first();
Assert.assertEquals(rs.getInt("inc_f1"), 1);
Assert.assertEquals(rs.getInt("inc_f2"), 9);
// ---------------------------------------- logicalDeleteWithVersionByPrimaryKey ---------------------------------------
// 验证sql
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY, 1L, 2L);
Assert.assertEquals(sql, "update tb set inc_f1 = inc_f1 + 1,inc_f2 = 9 where inc_f1 = 1 and id = 2");
// 验证执行
result = tbMapper.invoke(OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY, 1L, 2L);
Assert.assertEquals(result, 1);
rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb where id = 2");
rs.first();
Assert.assertEquals(rs.getInt("inc_f1"), 2);
Assert.assertEquals(rs.getInt("inc_f2"), 9);
}
});
// 自定义nextVersion
tool = MyBatisGeneratorTool.create("scripts/OptimisticLockerPlugin/mybatis-generator-with-LogicalDeletePlugin-customizedNextVersion.xml");
tool.generate(() -> DBHelper.resetDB("scripts/OptimisticLockerPlugin/init.sql"), new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// ---------------------------------------- logicalDeleteWithVersionByExample ---------------------------------------
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);
// 验证sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE, 0L, 100L, tbExample.getObject());
Assert.assertEquals(sql, "update tb set inc_f1 = 100,inc_f2 = 9 WHERE inc_f1 = 0 and ( ( id = '1' ) )");
// 验证执行
Object result = tbMapper.invoke(OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_EXAMPLE, 0L, 100L, tbExample.getObject());
Assert.assertEquals(result, 1);
ResultSet rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb where id = 1");
rs.first();
Assert.assertEquals(rs.getInt("inc_f1"), 100);
Assert.assertEquals(rs.getInt("inc_f2"), 9);
// ---------------------------------------- logicalDeleteWithVersionByPrimaryKey ---------------------------------------
// 验证sql
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY, 1L, 200L, 2L);
Assert.assertEquals(sql, "update tb set inc_f1 = 200,inc_f2 = 9 where inc_f1 = 1 and id = 2");
// 验证执行
result = tbMapper.invoke(OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY, 1L, 200L, 2L);
Assert.assertEquals(result, 1);
rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb where id = 2");
rs.first();
Assert.assertEquals(rs.getInt("inc_f1"), 200);
Assert.assertEquals(rs.getInt("inc_f2"), 9);
// ------------------------------------ Key -----------------------------------
ObjectUtil tbKeysMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbKeysMapper")));
ObjectUtil tbKeysKey = new ObjectUtil(loader, packagz + ".TbKeysKey");
tbKeysKey.set("key1", 2L);
tbKeysKey.set("key2", "k2");
sql = SqlHelper.getFormatMapperSql(tbKeysMapper.getObject(), OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY, 3L, 200L, tbKeysKey.getObject());
Assert.assertEquals(sql, "update tb_keys set inc_f1 = 200,inc_f2 = 9 where inc_f1 = 3 and key1 = 2 and key2 = 'k2'");
// 验证执行
result = tbKeysMapper.invoke(OptimisticLockerPlugin.METHOD_LOGICAL_DELETE_WITH_VERSION_BY_PRIMARY_KEY, 3L, 200L, tbKeysKey.getObject());
Assert.assertEquals(result, 1);
rs = DBHelper.execute(sqlSession.getConnection(), "select * from tb_keys where key1 = 2 and key2 = 'k2'");
rs.first();
Assert.assertEquals(rs.getInt("inc_f1"), 200);
Assert.assertEquals(rs.getInt("inc_f2"), 9);
}
});
}
/**
* 测试 updateWithVersionByExampleWithBLOBs
*/
@@ -151,6 +151,7 @@ public class ObjectUtil {
}
if (flag) {
method.setAccessible(true);
return method.invoke(this.object, args);
}
}
@@ -0,0 +1,75 @@
/*
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-03 17:34:11
*/
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',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
-- ----------------------------
INSERT INTO `tb` VALUES ('1', 'fd1', '0');
INSERT INTO `tb` VALUES ('2', 'fd2', '1');
INSERT INTO `tb` VALUES ('3', null, '3');
-- ----------------------------
-- Table structure for tb_keys
-- ----------------------------
DROP TABLE IF EXISTS `tb_keys`;
CREATE TABLE `tb_keys` (
`key1` bigint(20) NOT NULL 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',
PRIMARY KEY (`key1`,`key2`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
-- ----------------------------
INSERT INTO `tb_keys` VALUES ('1', 'key1', 'fd1', '0', '1');
INSERT INTO `tb_keys` VALUES ('2', 'key2', 'fd2', '1', '2');
INSERT INTO `tb_keys` VALUES ('3', 'key3', null, '3', '3');
-- ----------------------------
-- Table structure for tb_lombok
-- ----------------------------
DROP TABLE IF EXISTS `tb_lombok`;
CREATE TABLE `tb_lombok` (
`id` bigint(20) NOT NULL COMMENT '注释1',
`key1` varchar(20) NOT NULL,
`field1` varchar(10) COMMENT '注释2',
`inc_f1` smallint(3),
`field3` longtext,
`field4` longtext,
PRIMARY KEY (`id`,`key1`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_lombok
-- ----------------------------
INSERT INTO `tb_lombok` VALUES ('1', 'key1', 'fd1', '0', 'xx1', null);
INSERT INTO `tb_lombok` VALUES ('2', 'key2', 'fd2', '1', 'xx2', 'ss2');
INSERT INTO `tb_lombok` VALUES ('3', 'key3', null, '3', 'xx3', null);
@@ -0,0 +1,63 @@
<?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.IncrementsPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.LombokPlugin">
<property name="@Builder" value="true"/>
</plugin>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<!-- 给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="field2"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys">
<property name="incrementsColumns" value="inc_f1, field2"/>
</table>
<table tableName="tb_lombok">
<property name="incrementsColumns" value="inc_f1,id"/>
</table>
</context>
</generatorConfiguration>
@@ -0,0 +1,81 @@
/*
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-03 17:34:11
*/
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',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
-- ----------------------------
-- ----------------------------
-- Table structure for tb_keys
-- ----------------------------
DROP TABLE IF EXISTS `tb_keys`;
CREATE TABLE `tb_keys` (
`key1` bigint(20) NOT NULL COMMENT '注释1',
`key2` varchar(255) NOT NULL,
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`key1`,`key2`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
-- ----------------------------
-- ----------------------------
-- Table structure for tb_key_blob
-- ----------------------------
DROP TABLE IF EXISTS `tb_key_blob`;
CREATE TABLE `tb_key_blob` (
`id` bigint(20) NOT NULL COMMENT '注释1',
`key1` varchar(20) NOT NULL,
`field1` longtext COMMENT '注释2',
`field2` longtext,
PRIMARY KEY (`id`,`key1`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_key_blob
-- ----------------------------
-- ----------------------------
-- Table structure for tb_lombok
-- ----------------------------
DROP TABLE IF EXISTS `tb_lombok`;
CREATE TABLE `tb_lombok` (
`id` bigint(20) NOT NULL COMMENT '注释1',
`key1` varchar(20) NOT NULL,
`field1` varchar(10) COMMENT '注释2',
`is_find` tinyint(1),
`field3` longtext,
`field4` longtext,
PRIMARY KEY (`id`,`key1`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_lombok
-- ----------------------------
@@ -0,0 +1,48 @@
<?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.LombokPlugin">
<property name="@Builder" value="true"/>
</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"/>
<table tableName="tb_lombok"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,48 @@
<?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.LombokPlugin">
<property name="@NoArgsConstructor" value="true"/>
<property name="@AllArgsConstructor" value="true"/>
</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_lombok"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,45 @@
<?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.LombokPlugin"/>
<!--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_lombok"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,48 @@
<?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.LombokPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}"/>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<property name="constructorBased" value="true"/>
</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"/>
<table tableName="tb_key_blob"/>
</context>
</generatorConfiguration>
@@ -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.LombokPlugin">
<property name="@Builder" value="true"/>
<property name="@AllArgsConstructor" value="true"/>
<property name="@NoArgsConstructor" value="true"/>
</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"/>
<table tableName="tb_keys"/>
<table tableName="tb_key_blob"/>
</context>
</generatorConfiguration>
@@ -0,0 +1,71 @@
<?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.OptimisticLockerPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin">
<!-- 逻辑删除-已删除值 -->
<property name="logicalDeleteValue" value="9L"/>
<!-- 逻辑删除-未删除值 -->
<property name="logicalUnDeleteValue" value="0L"/>
</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="versionColumn" value="inc_f1"/>
<property name="logicalDeleteColumn" value="inc_f2"/>
<property name="customizedNextVersion" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys">
<property name="versionColumn" value="inc_f1"/>
<property name="logicalDeleteColumn" value="inc_f2"/>
<property name="customizedNextVersion" value="true"/>
</table>
</context>
</generatorConfiguration>
@@ -0,0 +1,62 @@
<?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.OptimisticLockerPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin">
<!-- 逻辑删除-已删除值 -->
<property name="logicalDeleteValue" value="9L"/>
<!-- 逻辑删除-未删除值 -->
<property name="logicalUnDeleteValue" value="0L"/>
</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="versionColumn" value="inc_f1"/>
<property name="logicalDeleteColumn" value="inc_f2"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>