Compare commits

..
15 Commits
17 changed files with 427 additions and 202 deletions
+19 -1
View File
@@ -30,7 +30,7 @@ Maven引用:
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.1</version>
<version>1.2.3</version>
</dependency>
```
---------------------------------------
@@ -346,6 +346,8 @@ public class Test {
this.tbMapper.batchInsert(list);
// !!!下面按需插入指定列(类似于insertSelective),需要数据Model属性对应Column获取插件(ModelColumnPlugin)插件
this.tbMapper.batchInsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime);
// 或者排除某些列
this.tbMapper.batchInsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -427,6 +429,7 @@ public class Test {
项目中我们有时需要获取数据Model对应数据库字段的名称,一般直接根据数据Model的属性就可以猜出数据库对应column的名字,可是有的时候当column使用了columnOverride或者columnRenamingRule时就需要去看数据库设计了,所以提供了这个插件获取model对应的数据库Column。
* 配合Example Criteria 增强插件(ExampleEnhancedPlugin)使用,这个插件还提供了asc()和desc()方法配合Example的orderBy方法效果更佳。
* 配合批量插入插件(BatchInsertPlugin)使用,batchInsertSelective(@Param("list") List<XXX> list, @Param("selective") XXX.Column ... insertColumns)。
* 提供静态excludes方法来进行快速反选。
插件:
```xml
@@ -481,6 +484,9 @@ public class Test {
this.tbMapper.batchInsert(list);
// 下面按需插入指定列(类似于insertSelective)
this.tbMapper.batchInsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime);
// 4. excludes 方法
this.tbMapper.batchInsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -607,6 +613,9 @@ public class Test {
.build(),
Tb.Column.field1
);
// 3. 排除某些列
this.tbMapper.insertSelective(tb, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag));
}
}
```
@@ -1075,6 +1084,15 @@ public class Test {
Tb.Column.field2
);
// 同理还有 selectByPrimaryKeySelective,selectOneByExampleSelective(SelectOneByExamplePlugin插件配合使用)方法
// 当然可以使用excludes
this.tbMapper.selectByExampleSelective(
new TbExample()
.createCriteria()
.andField1GreaterThan(1)
.example(),
Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)
);
}
}
```
+7 -2
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.1</version>
<version>1.2.4</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -85,6 +85,11 @@
<version>2.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
</dependencies>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++profiles++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -212,7 +217,7 @@
<connection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</connection>
<developerConnection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</developerConnection>
<url>https://github.com/itfsw/mybatis-generator-plugin</url>
<tag>V1.2.1</tag>
<tag>V1.2.4</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -16,10 +16,7 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.*;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
@@ -88,7 +85,7 @@ public class BatchInsertPlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mBatchInsert, introspectedTable);
// interface 增加方法
interfaze.addMethod(mBatchInsert);
FormatTools.addMethodWithBestPosition(interfaze, mBatchInsert);
logger.debug("itfsw(批量插入插件):" + interfaze.getType().getShortName() + "增加batchInsert方法。");
// 2. batchInsertSelective
@@ -102,7 +99,7 @@ public class BatchInsertPlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mBatchInsertSelective, introspectedTable);
// interface 增加方法
interfaze.addMethod(mBatchInsertSelective);
FormatTools.addMethodWithBestPosition(interfaze, mBatchInsertSelective);
logger.debug("itfsw(批量插入插件):" + interfaze.getType().getShortName() + "增加batchInsertSelective方法。");
return true;
@@ -1,6 +1,7 @@
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.enhanced.InnerInterface;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.InnerInterfaceWrapperToInnerClass;
@@ -91,7 +92,7 @@ public class ExampleEnhancedPlugin extends BasePlugin {
exampleMethod,
"return this.example;"
);
innerClass.addMethod(exampleMethod);
FormatTools.addMethodWithBestPosition(innerClass, exampleMethod);
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "增加工厂方法example");
}
@@ -116,7 +117,7 @@ public class ExampleEnhancedPlugin extends BasePlugin {
new Parameter(innerClass.getType(), "add")
);
commentGenerator.addGeneralMethodComment(addMethod, introspectedTable);
criteriaAddInterface.addMethod(addMethod);
FormatTools.addMethodWithBestPosition(criteriaAddInterface, addMethod);
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "." + criteriaAddInterface.getType().getShortName() + "增加方法add");
InnerClass innerClassWrapper = new InnerInterfaceWrapperToInnerClass(criteriaAddInterface);
@@ -140,7 +141,7 @@ public class ExampleEnhancedPlugin extends BasePlugin {
"}",
"return this;"
);
innerClass.addMethod(andIfMethod);
FormatTools.addMethodWithBestPosition(innerClass, andIfMethod);
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "增加方法andIf");
}
@@ -163,7 +164,7 @@ public class ExampleEnhancedPlugin extends BasePlugin {
"this.setOrderByClause(orderByClause);",
"return this;"
);
topLevelClass.addMethod(orderByMethod);
FormatTools.addMethodWithBestPosition(topLevelClass, orderByMethod);
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "增加方法orderBy");
// 添加orderBy
@@ -187,7 +188,7 @@ public class ExampleEnhancedPlugin extends BasePlugin {
"return this;"
);
topLevelClass.addMethod(orderByMethod1);
FormatTools.addMethodWithBestPosition(topLevelClass, orderByMethod1);
logger.debug("itfsw(Example增强插件):" + topLevelClass.getType().getShortName() + "增加方法orderBy(String ... orderByClauses)");
}
}
@@ -177,11 +177,11 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
mInc.addBodyLine("this.value = value;");
mInc.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "value"));
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
eIncrements.addMethod(mInc);
FormatTools.addMethodWithBestPosition(eIncrements, mInc);
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
eIncrements.addMethod(mValue);
FormatTools.addMethodWithBestPosition(eIncrements, mValue);
builderClass.addInnerEnum(eIncrements);
// 增加field
@@ -198,10 +198,10 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
// getter&setter
Method mGetter = JavaElementGeneratorTools.generateGetterMethod(fIncrements);
commentGenerator.addGetterComment(mGetter, introspectedTable, null);
topLevelClass.addMethod(mGetter);
FormatTools.addMethodWithBestPosition(topLevelClass, mGetter);
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
topLevelClass.addMethod(mSetter);
FormatTools.addMethodWithBestPosition(topLevelClass, mSetter);
// 增加判断方法
Method mHasIncsForColumn = JavaElementGeneratorTools.generateMethod(
IncrementsPlugin.METHOD_INC_CHECK,
@@ -17,6 +17,7 @@
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 org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
@@ -41,8 +42,8 @@ public class LimitPlugin extends BasePlugin {
@Override
public boolean validate(List<String> warnings) {
// 该插件只支持MYSQL
if ("com.mysql.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false){
warnings.add("itfsw:插件"+this.getClass().getTypeName()+"只支持MySQL数据库!");
if ("com.mysql.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false) {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "只支持MySQL数据库!");
return false;
}
return super.validate(warnings);
@@ -51,7 +52,6 @@ public class LimitPlugin extends BasePlugin {
/**
* ModelExample Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param topLevelClass
* @param introspectedTable
* @return
@@ -77,25 +77,25 @@ public class LimitPlugin extends BasePlugin {
);
commentGenerator.addFieldComment(rowsField, introspectedTable);
topLevelClass.addField(rowsField);
logger.debug("itfsw(MySQL分页插件):"+topLevelClass.getType().getShortName()+"增加offset和rows字段");
logger.debug("itfsw(MySQL分页插件):" + topLevelClass.getType().getShortName() + "增加offset和rows字段");
// 增加getter && setter 方法
Method mSetOffset = JavaElementGeneratorTools.generateSetterMethod(offsetField);
commentGenerator.addGeneralMethodComment(mSetOffset, introspectedTable);
topLevelClass.addMethod(mSetOffset);
FormatTools.addMethodWithBestPosition(topLevelClass, mSetOffset);
Method mGetOffset = JavaElementGeneratorTools.generateGetterMethod(offsetField);
commentGenerator.addGeneralMethodComment(mGetOffset, introspectedTable);
topLevelClass.addMethod(mGetOffset);
FormatTools.addMethodWithBestPosition(topLevelClass, mGetOffset);
Method mSetRows = JavaElementGeneratorTools.generateSetterMethod(rowsField);
commentGenerator.addGeneralMethodComment(mSetRows, introspectedTable);
topLevelClass.addMethod(mSetRows);
FormatTools.addMethodWithBestPosition(topLevelClass, mSetRows);
Method mGetRows = JavaElementGeneratorTools.generateGetterMethod(rowsField);
commentGenerator.addGeneralMethodComment(mGetRows, introspectedTable);
topLevelClass.addMethod(mGetRows);
logger.debug("itfsw(MySQL分页插件):"+topLevelClass.getType().getShortName()+"增加offset和rows的getter和setter实现。");
FormatTools.addMethodWithBestPosition(topLevelClass, mGetRows);
logger.debug("itfsw(MySQL分页插件):" + topLevelClass.getType().getShortName() + "增加offset和rows的getter和setter实现。");
// 提供几个快捷方法
Method setLimit = JavaElementGeneratorTools.generateMethod(
@@ -110,7 +110,7 @@ public class LimitPlugin extends BasePlugin {
"this.rows = rows;",
"return this;"
);
topLevelClass.addMethod(setLimit);
FormatTools.addMethodWithBestPosition(topLevelClass, setLimit);
Method setLimit2 = JavaElementGeneratorTools.generateMethod(
"limit",
@@ -126,8 +126,8 @@ public class LimitPlugin extends BasePlugin {
"this.rows = rows;",
"return this;"
);
topLevelClass.addMethod(setLimit2);
logger.debug("itfsw(MySQL分页插件):"+topLevelClass.getType().getShortName()+"增加limit方法。");
FormatTools.addMethodWithBestPosition(topLevelClass, setLimit2);
logger.debug("itfsw(MySQL分页插件):" + topLevelClass.getType().getShortName() + "增加limit方法。");
Method setPage = JavaElementGeneratorTools.generateMethod(
"page",
@@ -143,16 +143,16 @@ public class LimitPlugin extends BasePlugin {
"this.rows = pageSize;",
"return this;"
);
topLevelClass.addMethod(setPage);
logger.debug("itfsw(MySQL分页插件):"+topLevelClass.getType().getShortName()+"增加page方法");
FormatTools.addMethodWithBestPosition(topLevelClass, setPage);
logger.debug("itfsw(MySQL分页插件):" + topLevelClass.getType().getShortName() + "增加page方法");
// !!! clear 方法增加 offset 和 rows的清理
List<Method> methodList = topLevelClass.getMethods();
for (Method method: methodList){
if (method.getName().equals("clear")){
for (Method method : methodList) {
if (method.getName().equals("clear")) {
method.addBodyLine("rows = null;");
method.addBodyLine("offset = null;");
logger.debug("itfsw(MySQL分页插件):"+topLevelClass.getType().getShortName()+"修改clear方法,增加rows和offset字段的清空");
logger.debug("itfsw(MySQL分页插件):" + topLevelClass.getType().getShortName() + "修改clear方法,增加rows和offset字段的清空");
}
}
@@ -162,7 +162,6 @@ public class LimitPlugin extends BasePlugin {
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param element
* @param introspectedTable
* @return
@@ -176,7 +175,6 @@ public class LimitPlugin extends BasePlugin {
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param element
* @param introspectedTable
* @return
@@ -189,11 +187,10 @@ public class LimitPlugin extends BasePlugin {
/**
* 生成limit节点
*
* @param element
* @param introspectedTable
*/
public void generateLimitElement(XmlElement element, IntrospectedTable introspectedTable){
public void generateLimitElement(XmlElement element, IntrospectedTable introspectedTable) {
XmlElement ifLimitNotNullElement = new XmlElement("if");
ifLimitNotNullElement.addAttribute(new Attribute("test", "rows != null"));
@@ -209,6 +206,6 @@ public class LimitPlugin extends BasePlugin {
element.addElement(ifLimitNotNullElement);
logger.debug("itfsw(MySQL分页插件):"+introspectedTable.getMyBatis3XmlMapperFileName()+"selectByExample方法增加分页条件。");
logger.debug("itfsw(MySQL分页插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "selectByExample方法增加分页条件。");
}
}
@@ -165,7 +165,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// 添加方法说明
commentGenerator.addGeneralMethodComment(mLogicalDeleteByExample, introspectedTable);
// interface 增加方法
interfaze.addMethod(mLogicalDeleteByExample);
FormatTools.addMethodWithBestPosition(interfaze, mLogicalDeleteByExample);
logger.debug("itfsw(逻辑删除插件):" + interfaze.getType().getShortName() + "增加方法logicalDeleteByExample。");
// 2. 判断是否有主键,生成主键删除方法
@@ -192,7 +192,7 @@ public class LogicalDeletePlugin extends BasePlugin {
if (introspectedTable.getRules().generatePrimaryKeyClass()) {
FullyQualifiedJavaType type1 = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType());
importedTypes.add(type1);
mLogicalDeleteByPrimaryKey.addParameter(new Parameter(type1, "key"));
mLogicalDeleteByPrimaryKey.addParameter(new Parameter(type1, "key"));
mSelectByPrimaryKey.addParameter(new Parameter(type1, "key", "@Param(\"key\")"));
} else {
// no primary key class - fields are in the base class
@@ -229,7 +229,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// interface 增加方法
interfaze.addImportedTypes(importedTypes);
interfaze.addMethod(mLogicalDeleteByPrimaryKey);
FormatTools.addMethodWithBestPosition(interfaze, mLogicalDeleteByPrimaryKey);
logger.debug("itfsw(逻辑删除插件):" + interfaze.getType().getShortName() + "增加方法logicalDeleteByPrimaryKey。");
// 增强selectByPrimaryKey
@@ -256,13 +256,13 @@ public class LogicalDeletePlugin extends BasePlugin {
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
if (this.logicalDeleteColumn != null) {
// 1. 逻辑删除ByExample
XmlElement logicalDeleteByExample = new XmlElement("update");
XmlElement logicalDeleteByExample = new XmlElement("update");
logicalDeleteByExample.addAttribute(new Attribute("id", METHOD_LOGICAL_DELETE_BY_EXAMPLE));
logicalDeleteByExample.addAttribute(new Attribute("parameterType", "map")); //$NON-NLS-2$
commentGenerator.addComment(logicalDeleteByExample);
StringBuilder sb = new StringBuilder();
sb.append("update ");
sb.append("update ");
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
sb.append(" set ");
// 更新逻辑删除字段
@@ -294,7 +294,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// 2. 判断是否有主键,生成主键删除方法
if (introspectedTable.hasPrimaryKeyColumns()) {
XmlElement logicalDeleteByPrimaryKey = new XmlElement("update");
XmlElement logicalDeleteByPrimaryKey = new XmlElement("update");
logicalDeleteByPrimaryKey.addAttribute(new Attribute("id", METHOD_LOGICAL_DELETE_BY_PRIMARY_KEY));
String parameterClass;
@@ -304,7 +304,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// PK fields are in the base class. If more than on PK
// field, then they are coming in a map.
if (introspectedTable.getPrimaryKeyColumns().size() > 1) {
parameterClass = "map";
parameterClass = "map";
} else {
parameterClass = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
}
@@ -313,7 +313,7 @@ public class LogicalDeletePlugin extends BasePlugin {
commentGenerator.addComment(logicalDeleteByPrimaryKey);
StringBuilder sb1 = new StringBuilder();
sb1.append("update ");
sb1.append("update ");
sb1.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
sb1.append(" set ");
// 更新逻辑删除字段
@@ -346,7 +346,7 @@ public class LogicalDeletePlugin extends BasePlugin {
// 3. 增强selectByPrimaryKey
XmlElement selectByPrimaryKey = new XmlElement("select");
XmlElement selectByPrimaryKey = new XmlElement("select");
commentGenerator.addComment(selectByPrimaryKey);
selectByPrimaryKey.addAttribute(new Attribute("id", METHOD_SELECT_BY_PRIMARY_KEY_WITH_LOGICAL_DELETE));
@@ -361,22 +361,22 @@ public class LogicalDeletePlugin extends BasePlugin {
context.getCommentGenerator().addComment(selectByPrimaryKey);
sb = new StringBuilder();
sb.append("select ");
sb.append("select ");
if (stringHasValue(introspectedTable.getSelectByPrimaryKeyQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByPrimaryKeyQueryId());
sb.append("' as QUERYID,");
sb.append("' as QUERYID,");
}
selectByPrimaryKey.addElement(new TextElement(sb.toString()));
selectByPrimaryKey.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
if (introspectedTable.hasBLOBColumns()) {
selectByPrimaryKey.addElement(new TextElement(","));
selectByPrimaryKey.addElement(new TextElement(","));
selectByPrimaryKey.addElement(XmlElementGeneratorTools.getBlobColumnListElement(introspectedTable));
}
sb.setLength(0);
sb.append("from ");
sb.append("from ");
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectByPrimaryKey.addElement(new TextElement(sb.toString()));
@@ -436,18 +436,18 @@ public class LogicalDeletePlugin extends BasePlugin {
* @param topLevelClass
* @param introspectedTable
*/
private void generateModelMethodsAndFields(TopLevelClass topLevelClass, IntrospectedTable introspectedTable){
private void generateModelMethodsAndFields(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (this.logicalDeleteColumn != null) {
// 常量和逻辑删除方法跟随 逻辑删除列走
boolean flag = false;
for (Field field : topLevelClass.getFields()){
if (this.logicalDeleteColumn.getJavaProperty().equals(field.getName())){
for (Field field : topLevelClass.getFields()) {
if (this.logicalDeleteColumn.getJavaProperty().equals(field.getName())) {
flag = true;
break;
}
}
if (flag){
if (flag) {
ArrayList<Field> fields = (ArrayList<Field>) topLevelClass.getFields();
// 添加删除标志位常量
@@ -461,12 +461,6 @@ public class LogicalDeletePlugin extends BasePlugin {
} else {
logicalDeleteValue = this.logicalDeleteValue;
}
// TODO 过期
Field field = JavaElementGeneratorTools.generateStaticFinalField("DEL_FLAG_OFF", this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalDeleteValue);
field.addAnnotation("@Deprecated");
commentGenerator.addFieldComment(field, introspectedTable);
// 常量插入到第一位
fields.add(0, field);
Field logicalDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(this.logicalDeleteConstName, this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalDeleteValue);
commentGenerator.addFieldComment(logicalDeleteConstField, introspectedTable);
@@ -485,13 +479,6 @@ public class LogicalDeletePlugin extends BasePlugin {
logicalUnDeleteValue = this.logicalUnDeleteValue;
}
// TODO 过期
Field field1 = JavaElementGeneratorTools.generateStaticFinalField("DEL_FLAG_ON", this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalUnDeleteValue);
field1.addAnnotation("@Deprecated");
commentGenerator.addFieldComment(field1, introspectedTable);
// 常量插入到第一位
fields.add(0, field1);
Field logicalUnDeleteConstField = JavaElementGeneratorTools.generateStaticFinalField(this.logicalUnDeleteConstName, this.logicalDeleteColumn.getFullyQualifiedJavaType(), logicalUnDeleteValue);
commentGenerator.addFieldComment(logicalUnDeleteConstField, introspectedTable);
fields.add(0, logicalUnDeleteConstField);
@@ -505,7 +492,7 @@ public class LogicalDeletePlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mAndLogicalDeleted, introspectedTable);
Method logicalDeleteSetter = JavaBeansUtil.getJavaBeansSetter(this.logicalDeleteColumn, context, introspectedTable);
mAndLogicalDeleted.addBodyLine(logicalDeleteSetter.getName() +"(deleted ? " + this.logicalDeleteConstName + " : " + this.logicalUnDeleteConstName + ");");
mAndLogicalDeleted.addBodyLine(logicalDeleteSetter.getName() + "(deleted ? " + this.logicalDeleteConstName + " : " + this.logicalUnDeleteConstName + ");");
FormatTools.addMethodWithBestPosition(topLevelClass, mAndLogicalDeleted);
}
}
@@ -544,7 +531,7 @@ public class LogicalDeletePlugin extends BasePlugin {
StringBuilder equalToMethodName = new StringBuilder();
equalToMethodName.append(this.logicalDeleteColumn.getJavaProperty());
equalToMethodName.setCharAt(0, Character.toUpperCase(equalToMethodName.charAt(0)));
equalToMethodName.insert(0, "and");
equalToMethodName.insert(0, "and");
equalToMethodName.append("EqualTo");
sb.append(equalToMethodName);
sb.append("(" + modelName + "." + this.logicalDeleteConstName + ")");
@@ -555,7 +542,7 @@ public class LogicalDeletePlugin extends BasePlugin {
StringBuilder notEqualToMethodName = new StringBuilder();
notEqualToMethodName.append(this.logicalDeleteColumn.getJavaProperty());
notEqualToMethodName.setCharAt(0, Character.toUpperCase(notEqualToMethodName.charAt(0)));
notEqualToMethodName.insert(0, "and");
notEqualToMethodName.insert(0, "and");
notEqualToMethodName.append("NotEqualTo");
sb.append(notEqualToMethodName);
sb.append("(" + modelName + "." + this.logicalDeleteConstName + ")");
@@ -564,14 +551,7 @@ public class LogicalDeletePlugin extends BasePlugin {
method.addBodyLine(sb.toString());
innerClass.addMethod(method);
// TODO 过期方法
Method mAndDeleted = new Method(method);
mAndDeleted.setName("andDeleted");
mAndDeleted.addAnnotation("@Deprecated");
innerClass.addMethod(mAndDeleted);
logger.debug("itfsw(逻辑删除插件):" + topLevelClass.getType().getShortName() + "." + innerClass.getType().getShortName() + "增加andDeleted方法。");
FormatTools.addMethodWithBestPosition(innerClass, method);
}
}
}
@@ -17,6 +17,7 @@
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.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.InnerTypeFullyQualifiedJavaType;
@@ -116,7 +117,7 @@ public class ModelBuilderPlugin extends BasePlugin {
commentGenerator.addGeneralMethodComment(builder, introspectedTable);
builder.setStatic(true);
builder.addBodyLine("return new " + builderType.getShortName() + "();");
topLevelClass.addMethod(builder);
FormatTools.addMethodWithBestPosition(topLevelClass, builder);
commentGenerator.addClassComment(innerClass, introspectedTable);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + "增加内部Builder类。");
@@ -132,7 +133,7 @@ public class ModelBuilderPlugin extends BasePlugin {
constructor.setConstructor(true);
constructor.addBodyLine(new StringBuilder("this.obj = new ").append(topLevelClass.getType().getShortName()).append("();").toString());
commentGenerator.addGeneralMethodComment(constructor, introspectedTable);
innerClass.addMethod(constructor);
FormatTools.addMethodWithBestPosition(innerClass, constructor);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + ".Builder增加的构造方法。");
for (IntrospectedColumn introspectedColumn : columns) {
@@ -154,7 +155,7 @@ public class ModelBuilderPlugin extends BasePlugin {
// hook
if (PluginTools.getHook(IModelBuilderPluginHook.class).modelBuilderSetterMethodGenerated(method, topLevelClass, innerClass, introspectedColumn, introspectedTable)) {
innerClass.addMethod(method);
FormatTools.addMethodWithBestPosition(innerClass, method);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + ".Builder增加" + method.getName() + "方法(复合主键)。");
}
}
@@ -166,7 +167,7 @@ public class ModelBuilderPlugin extends BasePlugin {
);
build.addBodyLine("return this.obj;");
commentGenerator.addGeneralMethodComment(build, introspectedTable);
innerClass.addMethod(build);
FormatTools.addMethodWithBestPosition(innerClass, build);
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + ".Builder增加build方法。");
// hook
@@ -17,6 +17,7 @@
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 org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
@@ -33,6 +34,7 @@ import org.mybatis.generator.internal.util.JavaBeansUtil;
*/
public class ModelColumnPlugin extends BasePlugin {
public static final String ENUM_NAME = "Column"; // 内部Enum名
public static final String METHOD_EXCLUDES = "excludes"; // 方法名
/**
* Model Methods 生成
@@ -110,22 +112,22 @@ public class ModelColumnPlugin extends BasePlugin {
mValue.setReturnType(FullyQualifiedJavaType.getStringInstance());
mValue.addBodyLine("return this.column;");
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
innerEnum.addMethod(mValue);
FormatTools.addMethodWithBestPosition(innerEnum, mValue);
Method mGetValue = new Method("getValue");
mGetValue.setVisibility(JavaVisibility.PUBLIC);
mGetValue.setReturnType(FullyQualifiedJavaType.getStringInstance());
mGetValue.addBodyLine("return this.column;");
commentGenerator.addGeneralMethodComment(mGetValue, introspectedTable);
innerEnum.addMethod(mGetValue);
FormatTools.addMethodWithBestPosition(innerEnum, mGetValue);
Method mGetJavaProperty = JavaElementGeneratorTools.generateGetterMethod(javaPropertyField);
commentGenerator.addGeneralMethodComment(mGetJavaProperty, introspectedTable);
innerEnum.addMethod(mGetJavaProperty);
FormatTools.addMethodWithBestPosition(innerEnum, mGetJavaProperty);
Method mGetJdbcType = JavaElementGeneratorTools.generateGetterMethod(jdbcTypeField);
commentGenerator.addGeneralMethodComment(mGetJdbcType, introspectedTable);
innerEnum.addMethod(mGetJdbcType);
FormatTools.addMethodWithBestPosition(innerEnum, mGetJdbcType);
Method constructor = new Method(ENUM_NAME);
constructor.setConstructor(true);
@@ -136,7 +138,7 @@ public class ModelColumnPlugin extends BasePlugin {
constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "javaProperty"));
constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "jdbcType"));
commentGenerator.addGeneralMethodComment(constructor, introspectedTable);
innerEnum.addMethod(constructor);
FormatTools.addMethodWithBestPosition(innerEnum, constructor);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。");
// Enum枚举
@@ -163,16 +165,38 @@ public class ModelColumnPlugin extends BasePlugin {
desc.setReturnType(FullyQualifiedJavaType.getStringInstance());
desc.addBodyLine("return this.column + \" DESC\";");
commentGenerator.addGeneralMethodComment(desc, introspectedTable);
innerEnum.addMethod(desc);
FormatTools.addMethodWithBestPosition(innerEnum, desc);
Method asc = new Method("asc");
asc.setVisibility(JavaVisibility.PUBLIC);
asc.setReturnType(FullyQualifiedJavaType.getStringInstance());
asc.addBodyLine("return this.column + \" ASC\";");
commentGenerator.addGeneralMethodComment(asc, introspectedTable);
innerEnum.addMethod(asc);
FormatTools.addMethodWithBestPosition(innerEnum, asc);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加asc()和desc()方法。");
// excludes
topLevelClass.addImportedType("java.util.Arrays");
topLevelClass.addImportedType(FullyQualifiedJavaType.getNewArrayListInstance());
Method mExcludes = JavaElementGeneratorTools.generateMethod(
METHOD_EXCLUDES,
JavaVisibility.PUBLIC,
new FullyQualifiedJavaType(ENUM_NAME + "[]"),
new Parameter(innerEnum.getType(), "excludes", true)
);
commentGenerator.addGeneralMethodComment(mExcludes, introspectedTable);
mExcludes.setStatic(true);
JavaElementGeneratorTools.generateMethodBody(
mExcludes,
"ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values()));",
"if (excludes != null && excludes.length > 0) {",
"columns.removeAll(new ArrayList<>(Arrays.asList(excludes)));",
"}",
"return columns.toArray(new Column[]{});"
);
FormatTools.addMethodWithBestPosition(innerEnum, mExcludes);
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加excludes方法。");
return innerEnum;
}
}
@@ -38,64 +38,81 @@ import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
public class SelectOneByExamplePlugin extends BasePlugin {
public static final String METHOD_SELECT_ONE_BY_EXAMPLE = "selectOneByExample"; // 方法名
public static final String METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS = "selectOneByExampleWithBLOBs"; // 方法名
private XmlElement selectOneByExampleEle;
private XmlElement selectOneByExampleWithBLOBsEle;
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
// bug:26,27
this.selectOneByExampleWithBLOBsEle = null;
this.selectOneByExampleEle = null;
}
/**
* Java Client Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param method
* @param interfaze
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
// 方法生成 selectOneByExample
Method method = JavaElementGeneratorTools.generateMethod(
Method selectOneMethod = JavaElementGeneratorTools.generateMethod(
METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS,
JavaVisibility.DEFAULT,
JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example")
);
commentGenerator.addGeneralMethodComment(selectOneMethod, introspectedTable);
// hook
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).clientSelectOneByExampleWithBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable)) {
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, selectOneMethod);
logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExampleWithBLOBs方法。");
}
return super.clientSelectByExampleWithBLOBsMethodGenerated(method, interfaze, introspectedTable);
}
/**
* Java Client Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
@Override
public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
// 方法生成 selectOneByExample
Method selectOneMethod = JavaElementGeneratorTools.generateMethod(
METHOD_SELECT_ONE_BY_EXAMPLE,
JavaVisibility.DEFAULT,
JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example")
);
commentGenerator.addGeneralMethodComment(method, introspectedTable);
commentGenerator.addGeneralMethodComment(selectOneMethod, introspectedTable);
// hook
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).clientSelectOneByExampleWithoutBLOBsMethodGenerated(method, interfaze, introspectedTable)) {
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).clientSelectOneByExampleWithoutBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable)) {
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, method);
FormatTools.addMethodWithBestPosition(interfaze, selectOneMethod);
logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExample方法。");
}
// 方法生成 selectOneByExampleWithBLOBs !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()) {
// 方法生成 selectOneByExample
Method method1 = JavaElementGeneratorTools.generateMethod(
METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS,
JavaVisibility.DEFAULT,
JavaElementGeneratorTools.getModelTypeWithBLOBs(introspectedTable),
new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example")
);
commentGenerator.addGeneralMethodComment(method1, introspectedTable);
// hook
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).clientSelectOneByExampleWithBLOBsMethodGenerated(method1, interfaze, introspectedTable)) {
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, method1);
logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExampleWithBLOBs方法。");
}
}
return true;
return super.clientSelectByExampleWithoutBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable);
}
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param document
* @param element
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
// ------------------------------------ selectOneByExample ----------------------------------
// 生成查询语句
XmlElement selectOneElement = new XmlElement("select");
@@ -132,66 +149,89 @@ public class SelectOneByExamplePlugin extends BasePlugin {
// 只查询一条
selectOneElement.addElement(new TextElement("limit 1"));
this.selectOneByExampleEle = selectOneElement;
return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}
// hook
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).sqlMapSelectOneByExampleWithoutBLOBsElementGenerated(document, selectOneElement, introspectedTable)) {
// 添加到根节点
FormatTools.addElementWithBestPosition(document.getRootElement(), selectOneElement);
logger.debug("itfsw(查询单条数据插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加selectOneByExample方法。");
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param element
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
// 生成查询语句
XmlElement selectOneWithBLOBsElement = new XmlElement("select");
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(selectOneWithBLOBsElement);
// 添加ID
selectOneWithBLOBsElement.addAttribute(new Attribute("id", METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS));
// 添加返回类型
selectOneWithBLOBsElement.addAttribute(new Attribute("resultMap", introspectedTable.getResultMapWithBLOBsId()));
// 添加参数类型
selectOneWithBLOBsElement.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType()));
// 添加查询SQL
selectOneWithBLOBsElement.addElement(new TextElement("select"));
StringBuilder sb = new StringBuilder();
if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByExampleQueryId());
sb.append("' as QUERYID,");
selectOneWithBLOBsElement.addElement(new TextElement(sb.toString()));
}
// ------------------------------------ selectOneByExampleWithBLOBs ----------------------------------
// !!! 注意这里的行为不以有没有生成Model 的 WithBLOBs类为基准
if (introspectedTable.hasBLOBColumns()) {
// 生成查询语句
XmlElement selectOneWithBLOBsElement = new XmlElement("select");
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(selectOneWithBLOBsElement);
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
selectOneWithBLOBsElement.addElement(new TextElement(","));
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getBlobColumnListElement(introspectedTable));
// 添加ID
selectOneWithBLOBsElement.addAttribute(new Attribute("id", METHOD_SELECT_ONE_BY_EXAMPLE_WITH_BLOBS));
// 添加返回类型
selectOneWithBLOBsElement.addAttribute(new Attribute("resultMap", introspectedTable.getResultMapWithBLOBsId()));
// 添加参数类型
selectOneWithBLOBsElement.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType()));
// 添加查询SQL
selectOneWithBLOBsElement.addElement(new TextElement("select"));
sb.setLength(0);
sb.append("from ");
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectOneWithBLOBsElement.addElement(new TextElement(sb.toString()));
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getExampleIncludeElement(introspectedTable));
sb.setLength(0);
if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) {
sb.append('\'');
sb.append(introspectedTable.getSelectByExampleQueryId());
sb.append("' as QUERYID,");
selectOneWithBLOBsElement.addElement(new TextElement(sb.toString()));
}
XmlElement ifElement1 = new XmlElement("if");
ifElement1.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-2$
ifElement1.addElement(new TextElement("order by ${orderByClause}"));
selectOneWithBLOBsElement.addElement(ifElement1);
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getBaseColumnListElement(introspectedTable));
selectOneWithBLOBsElement.addElement(new TextElement(","));
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getBlobColumnListElement(introspectedTable));
// 只查询一条
selectOneWithBLOBsElement.addElement(new TextElement("limit 1"));
sb.setLength(0);
sb.append("from ");
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
selectOneWithBLOBsElement.addElement(new TextElement(sb.toString()));
selectOneWithBLOBsElement.addElement(XmlElementGeneratorTools.getExampleIncludeElement(introspectedTable));
XmlElement ifElement1 = new XmlElement("if");
ifElement1.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-2$
ifElement1.addElement(new TextElement("order by ${orderByClause}"));
selectOneWithBLOBsElement.addElement(ifElement1);
// 只查询一条
selectOneWithBLOBsElement.addElement(new TextElement("limit 1"));
this.selectOneByExampleWithBLOBsEle = selectOneWithBLOBsElement;
return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable);
}
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param document
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
if (selectOneByExampleEle != null) {
// hook
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).sqlMapSelectOneByExampleWithBLOBsElementGenerated(document, selectOneWithBLOBsElement, introspectedTable)) {
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).sqlMapSelectOneByExampleWithoutBLOBsElementGenerated(document, selectOneByExampleEle, introspectedTable)) {
// 添加到根节点
FormatTools.addElementWithBestPosition(document.getRootElement(), selectOneWithBLOBsElement);
FormatTools.addElementWithBestPosition(document.getRootElement(), selectOneByExampleEle);
logger.debug("itfsw(查询单条数据插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加selectOneByExample方法。");
}
}
if (selectOneByExampleWithBLOBsEle != null) {
// hook
if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).sqlMapSelectOneByExampleWithBLOBsElementGenerated(document, selectOneByExampleWithBLOBsEle, introspectedTable)) {
// 添加到根节点
FormatTools.addElementWithBestPosition(document.getRootElement(), selectOneByExampleWithBLOBsEle);
logger.debug("itfsw(查询单条数据插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加selectOneByExampleWithBLOBs方法。");
}
}
return true;
}
}
@@ -20,10 +20,7 @@ import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.ISelectOneByExamplePluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
@@ -44,6 +41,8 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
public static final String METHOD_SELECT_BY_PRIMARY_KEY_SELECTIVE = "selectByPrimaryKeySelective";
public static final String METHOD_SELECT_ONE_BY_EXAMPLE_SELECTIVE = "selectOneByExampleSelective";
public static final String ID_FOR_PROPERTY_BASED_RESULT_MAP = "BasePropertyResultMap";
private XmlElement selectByExampleSelectiveEle;
private XmlElement selectByPrimaryKeySelectiveEle;
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
@@ -62,6 +61,19 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
return super.validate(warnings);
}
/**
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param introspectedTable
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
// bug:26,27
this.selectByExampleSelectiveEle = null;
this.selectByPrimaryKeySelectiveEle = null;
}
// =========================================== client 方法生成 ===================================================
@Override
@@ -120,18 +132,24 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
// ============================================== sqlMap 生成 ===================================================
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
this.selectByExampleSelectiveEle = this.generateSelectSelectiveElement(METHOD_SELECT_BY_EXAMPLE_SELECTIVE, introspectedTable, false, true);
return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
if (!introspectedTable.hasBLOBColumns()) {
this.selectByExampleSelectiveEle = this.generateSelectSelectiveElement(METHOD_SELECT_BY_EXAMPLE_SELECTIVE, introspectedTable, false, true);
}
return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
this.selectByPrimaryKeySelectiveEle = this.generateSelectSelectiveElement(METHOD_SELECT_BY_PRIMARY_KEY_SELECTIVE, introspectedTable, false, false);
return super.sqlMapSelectByPrimaryKeyElementGenerated(element, introspectedTable);
}
@@ -156,15 +174,18 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) {
resultMapEle.addElement(XmlElementGeneratorTools.generateResultMapResultElement("result", introspectedColumn));
}
document.getRootElement().getElements().add(0, resultMapEle);
document.getRootElement().addElement(0, resultMapEle);
}
// 1. selectByExampleSelective 方法
FormatTools.addElementWithBestPosition(document.getRootElement(), this.generateSelectSelectiveElement(METHOD_SELECT_BY_EXAMPLE_SELECTIVE, introspectedTable, false, true));
if (this.selectByExampleSelectiveEle != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.selectByExampleSelectiveEle);
}
// 2. selectByPrimaryKeySelective
FormatTools.addElementWithBestPosition(document.getRootElement(), this.generateSelectSelectiveElement(METHOD_SELECT_BY_PRIMARY_KEY_SELECTIVE, introspectedTable, false, false));
if (this.selectByPrimaryKeySelectiveEle != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.selectByPrimaryKeySelectiveEle);
}
return true;
}
@@ -16,10 +16,7 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.IUpsertPluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
@@ -96,7 +93,7 @@ public class UpsertPlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mUpsert, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsert);
FormatTools.addMethodWithBestPosition(interfaze, mUpsert);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsert方法。");
// ====================================== upsertWithBLOBs ======================================
@@ -110,7 +107,7 @@ public class UpsertPlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mUpsertWithBLOBs, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertWithBLOBs);
FormatTools.addMethodWithBestPosition(interfaze, mUpsertWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsert方法。");
}
@@ -127,7 +124,7 @@ public class UpsertPlugin extends BasePlugin {
// hook
if (PluginTools.getHook(IUpsertPluginHook.class).clientUpsertSelectiveMethodGenerated(mUpsertSelective, interfaze, introspectedTable)) {
// interface 增加方法
interfaze.addMethod(mUpsertSelective);
FormatTools.addMethodWithBestPosition(interfaze, mUpsertSelective);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertSelective方法。");
}
@@ -142,7 +139,7 @@ public class UpsertPlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mUpsertByExample, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertByExample);
FormatTools.addMethodWithBestPosition(interfaze, mUpsertByExample);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExample方法。");
// ====================================== upsertByExampleWithBLOBs ======================================
@@ -157,7 +154,7 @@ public class UpsertPlugin extends BasePlugin {
);
commentGenerator.addGeneralMethodComment(mUpsertByExampleWithBLOBs, introspectedTable);
// interface 增加方法
interfaze.addMethod(mUpsertByExampleWithBLOBs);
FormatTools.addMethodWithBestPosition(interfaze, mUpsertByExampleWithBLOBs);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExample方法。");
}
@@ -173,7 +170,7 @@ public class UpsertPlugin extends BasePlugin {
// hook
if (PluginTools.getHook(IUpsertPluginHook.class).clientUpsertByExampleSelectiveMethodGenerated(mUpsertByExampleSelective, interfaze, introspectedTable)) {
// interface 增加方法
interfaze.addMethod(mUpsertByExampleSelective);
FormatTools.addMethodWithBestPosition(interfaze, mUpsertByExampleSelective);
logger.debug("itfsw(存在即更新插件):" + interfaze.getType().getShortName() + "增加upsertByExampleSelective方法。");
}
}
@@ -16,12 +16,10 @@
package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.ModelColumnPlugin;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement;
@@ -29,6 +27,8 @@ import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* ---------------------------------------------------------------------------
@@ -54,9 +54,43 @@ public class FormatTools {
* @param method
*/
public static void addMethodWithBestPosition(Interface interfacz, Method method) {
// import
Set<FullyQualifiedJavaType> importTypes = new TreeSet<>();
// 返回
if (method.getReturnType() != null) {
importTypes.add(method.getReturnType());
importTypes.addAll(method.getReturnType().getTypeArguments());
}
// 参数 比较特殊的是ModelColumn生成的Column
for (Parameter parameter : method.getParameters()) {
boolean flag = true;
for (String annotation : parameter.getAnnotations()) {
if (annotation.startsWith("@Param")) {
importTypes.add(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param"));
if (annotation.matches(".*selective.*") && parameter.getType().getShortName().equals(ModelColumnPlugin.ENUM_NAME)) {
flag = false;
}
}
}
if (flag) {
importTypes.add(parameter.getType());
importTypes.addAll(parameter.getType().getTypeArguments());
}
}
interfacz.addImportedTypes(importTypes);
addMethodWithBestPosition(method, interfacz.getMethods());
}
/**
* 在最佳位置添加方法
* @param innerEnum
* @param method
*/
public static void addMethodWithBestPosition(InnerEnum innerEnum, Method method) {
addMethodWithBestPosition(method, innerEnum.getMethods());
}
/**
* 在最佳位置添加方法
* @param topLevelClass
@@ -141,7 +141,7 @@ public class LogicalDeletePluginTest {
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andDeleted", true);
criteria.invoke("andLogicalDeleted", true);
criteria.invoke("andIdEqualTo", 3l);
@@ -16,16 +16,15 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.AbstractShellCallback;
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool;
import com.itfsw.mybatis.generator.plugins.tools.ObjectUtil;
import com.itfsw.mybatis.generator.plugins.tools.*;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Array;
import java.sql.SQLException;
/**
@@ -41,7 +40,7 @@ public class ModelColumnPluginTest {
* 初始化数据库
*/
@BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException {
public static void init() throws SQLException, IOException {
DBHelper.createDB("scripts/ModelColumnPlugin/init.sql");
}
@@ -49,7 +48,7 @@ public class ModelColumnPluginTest {
* 测试生成的model
*/
@Test
public void test() throws Exception {
public void testModel() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ModelColumnPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() {
@Override
@@ -78,6 +77,63 @@ public class ModelColumnPluginTest {
Assert.assertEquals(TbKeysColumnKey1.invoke("value"), "key_1");
ObjectUtil TbKeysColumnField1 = new ObjectUtil(loader, packagz + ".TbKeys$Column#field1");
Assert.assertEquals(TbKeysColumnField1.invoke("value"), "field_1");
// 5. excludes 方法
// 不排除
Object columns = Array.newInstance(TbColumnField1.getCls(), 0);
Object[] result = (Object[])(MethodUtils.invokeStaticMethod(Class.forName(packagz + ".Tb$Column"), "excludes", columns));
Assert.assertEquals(result.length, 5);
// 排除两个
columns = Array.newInstance(TbColumnField1.getCls(), 2);
Array.set(columns, 0, TbColumnField1.getObject());
Array.set(columns, 1, TbColumnTsIncF2.getObject());
result = (Object[])(MethodUtils.invokeStaticMethod(Class.forName(packagz + ".Tb$Column"), "excludes", columns));
Assert.assertEquals(result.length, 3);
for (Object obj : result){
ObjectUtil column = new ObjectUtil(obj);
if (column.invoke("value").equals("field_1") || column.invoke("value").equals("inc_f2")){
Assert.assertTrue(false);
}
}
}
});
}
/**
* 测试excludes
*/
@Test
public void testExcludes() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ModelColumnPlugin/mybatis-generator-with-SeleciveEnhancedPlugin.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb");
tb.set("id", 121L);
tb.set("incF3", 10L);
tb.set("tsIncF2", 5L);
// selective
ObjectUtil TbColumnId = new ObjectUtil(loader, packagz + ".Tb$Column#id");
ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2");
Object columns = Array.newInstance(TbColumnField1.getCls(), 3);
Array.set(columns, 0, TbColumnId.getObject());
Array.set(columns, 1, TbColumnField1.getObject());
Array.set(columns, 2, TbColumnTsIncF2.getObject());
// sql(指定列)
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( id , field_1 , inc_f2 ) values ( 121 , 'null' , 5 )");
// sql(排除列)
columns = MethodUtils.invokeStaticMethod(Class.forName(packagz + ".Tb$Column"), "excludes", columns);
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject(), columns);
Assert.assertEquals(sql, "insert into tb ( inc_f1 , inc_f3 ) values ( null , 10 )");
Object result = tbMapper.invoke("insertSelective", tb.getObject(), columns);
Assert.assertEquals(result, 1);
}
});
}
@@ -20,11 +20,11 @@ SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field_1` varchar(255) DEFAULT NULL COMMENT '注释2',
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
`id` bigint(20) AUTO_INCREMENT COMMENT '注释1',
`field_1` varchar(255) COMMENT '注释2',
`inc_f1` bigint(20) DEFAULT '0',
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin">
<property name="allowMultiQueries" value="true"/>
</plugin>
<plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>