Commit 9ce992c7 authored by hewei's avatar hewei

增强Criteria的链式调用,添加andIf(boolean addIf, CriteriaAdd add)方法,实现链式调用中按条件增加查询语句

parent ed19ffa9
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
* 查询单条数据插件 * 查询单条数据插件
* MySQL分页插件 * MySQL分页插件
* 数据Model链式构建插件 * 数据Model链式构建插件
* Example Criteria 增强插件 * Example Criteria 增强插件(example,andIf)
* Example 目标包修改插件 * Example 目标包修改插件
--------------------------------------- ---------------------------------------
...@@ -141,8 +141,9 @@ public class Test { ...@@ -141,8 +141,9 @@ public class Test {
} }
} }
``` ```
### 4. Example Criteria 增强插件 ### 4. Example Criteria 增强插件(example,andIf)
表Example增加Criteria的快速返回example()方法。 * 表Example增加Criteria的快速返回example()方法。
* Criteria链式调用增强,以前如果有按条件增加的查询语句会打乱链式查询构建,现在有了andIf(boolean ifAdd, CriteriaAdd add)方法可一直使用链式调用下去。
插件: 插件:
```xml ```xml
<!-- Example Criteria 增强插件 --> <!-- Example Criteria 增强插件 -->
...@@ -152,12 +153,51 @@ public class Test { ...@@ -152,12 +153,51 @@ public class Test {
```java ```java
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
// -----------------------------------example-----------------------------------
// 表Example.Criteria增加了工厂方法example()支持,使用后可链式构建查询条件使用example()返回Example对象 // 表Example.Criteria增加了工厂方法example()支持,使用后可链式构建查询条件使用example()返回Example对象
TbExample ex = new TbExample() TbExample ex = new TbExample()
.createCriteria() .createCriteria()
.andField1EqualTo(1) .andField1EqualTo(1)
.andField2LessThan(100) .andField2EqualTo("xxx")
.example(); .example();
this.tbMapper.selectByExample(ex);
// -----------------------------------andIf-----------------------------------
// Criteria增强了链式调用,现在一些按条件增加的查询条件不会打乱链式调用了
// old
TbExample oldEx = new TbExample();
TbExample.Criteria criteria = oldEx
.createCriteria()
.andField1EqualTo(1)
.andField2EqualTo("xxx");
// 如果随机数大于0.5,附加Field3查询条件
if (Math.random() > 0.5){
criteria.andField3EqualTo(2)
.andField4EqualTo(new Date());
}
this.tbMapper.selectByExample(oldEx);
// new
TbExample newEx;
newEx = new TbExample()
.createCriteria()
.andField1EqualTo(1)
.andField2EqualTo("xxx")
// 如果随机数大于0.5,附加Field3查询条件
.andIf(Math.random() > 0.5, new TbExample.Criteria.CriteriaAdd() {
@Override
public TbExample.Criteria add(TbExample.Criteria add) {
return add.andField3EqualTo(2)
.andField4EqualTo(new Date());
}
})
// 当然最简洁的写法是采用java8的Lambda表达式,当然你的项目是Java8+
.andIf(Math.random() > 0.5, add -> add
.andField3EqualTo(2)
.andField4EqualTo(new Date())
)
.example();
this.tbMapper.selectByExample(newEx);
} }
} }
``` ```
......
...@@ -17,6 +17,8 @@ ...@@ -17,6 +17,8 @@
package com.itfsw.mybatis.generator.plugins; package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.CommentTools; import com.itfsw.mybatis.generator.plugins.utils.CommentTools;
import com.itfsw.mybatis.generator.plugins.utils.InnerInterface;
import com.itfsw.mybatis.generator.plugins.utils.InnerInterfaceWrapperToInnerClass;
import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*; import org.mybatis.generator.api.dom.java.*;
...@@ -55,7 +57,10 @@ public class CriteriaBuilderPlugin extends PluginAdapter { ...@@ -55,7 +57,10 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
List<InnerClass> innerClasses = topLevelClass.getInnerClasses(); List<InnerClass> innerClasses = topLevelClass.getInnerClasses();
for (InnerClass innerClass : innerClasses) { for (InnerClass innerClass : innerClasses) {
if ("Criteria".equals(innerClass.getType().getShortName())) { if ("Criteria".equals(innerClass.getType().getShortName())) {
// 工厂方法
addFactoryMethodToCriteria(topLevelClass, innerClass, introspectedTable); addFactoryMethodToCriteria(topLevelClass, innerClass, introspectedTable);
// andIf
addAndIfMethodToCriteria(topLevelClass, innerClass, introspectedTable);
} }
} }
...@@ -100,4 +105,45 @@ public class CriteriaBuilderPlugin extends PluginAdapter { ...@@ -100,4 +105,45 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
innerClass.addMethod(method); innerClass.addMethod(method);
logger.debug("itfsw:CriteriaBuilder增加工厂方法example"); logger.debug("itfsw:CriteriaBuilder增加工厂方法example");
} }
/**
* 增强Criteria的链式调用,添加andIf(boolean addIf, CriteriaAdd add)方法,实现链式调用中按条件增加查询语句
*
* @param topLevelClass
* @param innerClass
* @param introspectedTable
*/
private void addAndIfMethodToCriteria(TopLevelClass topLevelClass, InnerClass innerClass, IntrospectedTable introspectedTable){
// 添加接口CriteriaAdd
InnerInterface criteriaAddInterface = new InnerInterface("ICriteriaAdd");
criteriaAddInterface.setVisibility(JavaVisibility.PUBLIC);
CommentTools.addInterfaceComment(criteriaAddInterface, introspectedTable);
// ICriteriaAdd增加接口add
Method addMethod = new Method("add");
addMethod.setReturnType(innerClass.getType());
addMethod.addParameter(new Parameter(innerClass.getType(), "add"));
CommentTools.addGeneralMethodComment(addMethod, introspectedTable);
criteriaAddInterface.addMethod(addMethod);
logger.debug("itfsw:Criteria.ICriteriaAdd增加接口add");
InnerClass innerClassWrapper = new InnerInterfaceWrapperToInnerClass(criteriaAddInterface);
innerClass.addInnerClass(innerClassWrapper);
// 添加andIf方法
Method method = new Method("andIf");
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(innerClass.getType());
method.addParameter(new Parameter(FullyQualifiedJavaType.getBooleanPrimitiveInstance(), "ifAdd"));
method.addParameter(new Parameter(criteriaAddInterface.getType(), "add"));
method.addBodyLine("if (ifAdd) {");
method.addBodyLine("add.add(this);");
method.addBodyLine("}");
method.addBodyLine("return this;");
CommentTools.addGeneralMethodComment(method, introspectedTable);
innerClass.addMethod(method);
logger.debug("itfsw:Criteria增加方法andIf");
}
} }
...@@ -19,6 +19,7 @@ package com.itfsw.mybatis.generator.plugins.utils; ...@@ -19,6 +19,7 @@ package com.itfsw.mybatis.generator.plugins.utils;
import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass; 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.Method;
import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement; import org.mybatis.generator.api.dom.xml.XmlElement;
...@@ -111,4 +112,24 @@ public class CommentTools { ...@@ -111,4 +112,24 @@ public class CommentTools {
xmlElement.addElement(new TextElement("-->")); //$NON-NLS-1$ xmlElement.addElement(new TextElement("-->")); //$NON-NLS-1$
} }
/**
* 生成通用接口注解
*
* @param interf 接口
* @param introspectedTable 表
*/
public static void addInterfaceComment(Interface interf, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
interf.addJavaDocLine("/**"); //$NON-NLS-1$
interf.addJavaDocLine(" * 这是Mybatis Generator拓展插件生成的接口(请勿删除)."); //$NON-NLS-1$
sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
interf.addJavaDocLine(sb.toString());
interf.addJavaDocLine(" *");
interf.addJavaDocLine(" * "+MergeConstants.NEW_ELEMENT_TAG);
interf.addJavaDocLine(" * @author hewei");
interf.addJavaDocLine(" */"); //$NON-NLS-1$
}
} }
/*
*
* * Copyright (c) 2014.
* *
* * 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 org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.*;
import java.util.Iterator;
import java.util.Set;
import static org.mybatis.generator.api.dom.OutputUtilities.*;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
/**
* ---------------------------------------------------------------------------
* 内部接口
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/12 17:53
* ---------------------------------------------------------------------------
*/
public class InnerInterface extends Interface{
public InnerInterface(FullyQualifiedJavaType type) {
super(type);
}
public InnerInterface(String type) {
super(type);
}
/**
* 格式化后内容,因为是内部接口,需要增加缩进
*
* @param indentLevel the indent level
* @param compilationUnit the compilation unit
* @return the formatted content
*/
public String getFormattedContent(int indentLevel, CompilationUnit compilationUnit) {
StringBuilder sb = new StringBuilder();
for (String commentLine : getFileCommentLines()) {
sb.append(commentLine);
newLine(sb);
}
if (stringHasValue(getType().getPackageName())) {
sb.append("package "); //$NON-NLS-1$
sb.append(getType().getPackageName());
sb.append(';');
newLine(sb);
newLine(sb);
}
for (String staticImport : getStaticImports()) {
sb.append("import static "); //$NON-NLS-1$
sb.append(staticImport);
sb.append(';');
newLine(sb);
}
if (getStaticImports().size() > 0) {
newLine(sb);
}
Set<String> importStrings = calculateImports(getImportedTypes());
for (String importString : importStrings) {
sb.append(importString);
newLine(sb);
}
if (importStrings.size() > 0) {
newLine(sb);
}
addFormattedJavadoc(sb, indentLevel);
addFormattedAnnotations(sb, indentLevel);
OutputUtilities.javaIndent(sb, indentLevel);
sb.append(getVisibility().getValue());
if (isFinal()) {
sb.append("final "); //$NON-NLS-1$
}
sb.append("interface "); //$NON-NLS-1$
sb.append(getType().getShortName());
if (getSuperInterfaceTypes().size() > 0) {
sb.append(" extends "); //$NON-NLS-1$
boolean comma = false;
for (FullyQualifiedJavaType fqjt : getSuperInterfaceTypes()) {
if (comma) {
sb.append(", "); //$NON-NLS-1$
} else {
comma = true;
}
sb.append(JavaDomUtils.calculateTypeName(this, fqjt));
}
}
sb.append(" {"); //$NON-NLS-1$
indentLevel++;
Iterator<Method> mtdIter = getMethods().iterator();
while (mtdIter.hasNext()) {
newLine(sb);
Method method = mtdIter.next();
sb.append(method.getFormattedContent(indentLevel, true, this));
if (mtdIter.hasNext()) {
newLine(sb);
}
}
indentLevel--;
newLine(sb);
javaIndent(sb, indentLevel);
sb.append('}');
return sb.toString();
}
}
/*
*
* * Copyright (c) 2014.
* *
* * 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 org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
/**
* ---------------------------------------------------------------------------
* 把InnerInterface包装成InnerClass(Mybatis Generator 没有提供内部接口实现)
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/12 17:40
* ---------------------------------------------------------------------------
*/
public class InnerInterfaceWrapperToInnerClass extends InnerClass{
private InnerInterface innerInterface; // 内部接口
public InnerInterfaceWrapperToInnerClass(FullyQualifiedJavaType type) {
super(type);
}
public InnerInterfaceWrapperToInnerClass(String typeName) {
super(typeName);
}
public InnerInterfaceWrapperToInnerClass(InnerInterface innerInterface){
super(innerInterface.getType());
this.innerInterface = innerInterface;
}
/**
* 重写获取Java内容方法,调用InnerInterface的实现
*
* @param indentLevel
* @param compilationUnit
* @return
*/
@Override
public String getFormattedContent(int indentLevel, CompilationUnit compilationUnit) {
return this.innerInterface.getFormattedContent(indentLevel, compilationUnit);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment