fix#65:selectByExampleSelective 不支持分页

This commit is contained in:
hewei
2018-12-18 15:33:29 +08:00
parent 59a175be48
commit 2d3f7c377f
6 changed files with 174 additions and 8 deletions
@@ -19,9 +19,11 @@ 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.hook.ISelectSelectivePluginHook;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
@@ -35,7 +37,7 @@ import java.util.List;
* @time:2016/12/29 18:14
* ---------------------------------------------------------------------------
*/
public class LimitPlugin extends BasePlugin {
public class LimitPlugin extends BasePlugin implements ISelectSelectivePluginHook {
/**
* {@inheritDoc}
*/
@@ -169,7 +171,7 @@ public class LimitPlugin extends BasePlugin {
*/
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
this.generateLimitElement(element, introspectedTable);
this.generateLimitElement(element);
return true;
}
@@ -182,16 +184,23 @@ public class LimitPlugin extends BasePlugin {
*/
@Override
public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
this.generateLimitElement(element, introspectedTable);
this.generateLimitElement(element);
return true;
}
// ============================================ ISelectSelectivePluginHook ==========================================
@Override
public boolean sqlMapSelectByExampleSelectiveElementGenerated(Document document, XmlElement element, IntrospectedTable introspectedTable) {
this.generateLimitElementWithExample(element);
return false;
}
/**
* 生成limit节点
* @param element
* @param introspectedTable
*/
public void generateLimitElement(XmlElement element, IntrospectedTable introspectedTable) {
private void generateLimitElement(XmlElement element) {
XmlElement ifLimitNotNullElement = new XmlElement("if");
ifLimitNotNullElement.addAttribute(new Attribute("test", "rows != null"));
@@ -206,7 +215,26 @@ public class LimitPlugin extends BasePlugin {
ifLimitNotNullElement.addElement(ifOffsetNullElement);
element.addElement(ifLimitNotNullElement);
}
logger.debug("itfsw(MySQL分页插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "selectByExample方法增加分页条件。");
/**
* 生成limit节点
* @param element
*/
private void generateLimitElementWithExample(XmlElement element) {
XmlElement ifLimitNotNullElement = new XmlElement("if");
ifLimitNotNullElement.addAttribute(new Attribute("test", "example.rows != null"));
XmlElement ifOffsetNotNullElement = new XmlElement("if");
ifOffsetNotNullElement.addAttribute(new Attribute("test", "example.offset != null"));
ifOffsetNotNullElement.addElement(new TextElement("limit ${example.offset}, ${example.rows}"));
ifLimitNotNullElement.addElement(ifOffsetNotNullElement);
XmlElement ifOffsetNullElement = new XmlElement("if");
ifOffsetNullElement.addAttribute(new Attribute("test", "example.offset == null"));
ifOffsetNullElement.addElement(new TextElement("limit ${example.rows}"));
ifLimitNotNullElement.addElement(ifOffsetNullElement);
element.addElement(ifLimitNotNullElement);
}
}
@@ -18,6 +18,7 @@ package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.ISelectOneByExamplePluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.ISelectSelectivePluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
@@ -180,6 +181,7 @@ public class SelectSelectivePlugin extends BasePlugin implements ISelectOneByExa
// 1. selectByExampleSelective 方法
if (this.selectByExampleSelectiveEle != null) {
FormatTools.addElementWithBestPosition(document.getRootElement(), this.selectByExampleSelectiveEle);
PluginTools.getHook(ISelectSelectivePluginHook.class).sqlMapSelectByExampleSelectiveElementGenerated(document, this.selectByExampleSelectiveEle, introspectedTable);
}
// 2. selectByPrimaryKeySelective
@@ -50,9 +50,10 @@ public class HookAggregator implements IUpsertPluginHook,
ISelectOneByExamplePluginHook,
ITableConfigurationHook,
ILombokPluginHook,
ILogicalDeletePluginHook {
ILogicalDeletePluginHook,
ISelectSelectivePluginHook {
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class); // 日志
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class);
private final static HookAggregator instance = new HookAggregator();
private Context context;
@@ -343,4 +344,15 @@ public class HookAggregator implements IUpsertPluginHook,
return true;
}
// ============================================= ISelectSelectivePluginHook ==============================================
@Override
public boolean sqlMapSelectByExampleSelectiveElementGenerated(Document document, XmlElement element, IntrospectedTable introspectedTable) {
for (ISelectSelectivePluginHook plugin : this.getPlugins(ISelectSelectivePluginHook.class)) {
if (!plugin.sqlMapSelectByExampleSelectiveElementGenerated(document, element, introspectedTable)) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2018.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itfsw.mybatis.generator.plugins.utils.hook;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/12/18 14:57
* ---------------------------------------------------------------------------
*/
public interface ISelectSelectivePluginHook {
boolean sqlMapSelectByExampleSelectiveElementGenerated(Document document, XmlElement element, IntrospectedTable introspectedTable);
}
@@ -25,6 +25,7 @@ import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.List;
@@ -95,4 +96,39 @@ public class LimitPluginTest {
}
});
}
/**
* 整合SelectSelectivePlugin
* @throws Exception
*/
@Test
public void testWithSelectSelectivePlugin() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LimitPlugin/mybatis-generator-with-SelectSelectivePlugin.xml");
tool.generate(new AbstractShellCallback() {
@Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 测试limit 方法
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample");
tbExample.invoke("limit", 5);
ObjectUtil columnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1");
// java 动态参数不能有两个会冲突,最后一个封装成Array!!!必须使用反射创建指定类型数组,不然调用invoke对了可变参数会检查类型!
Object columns = Array.newInstance(columnField1.getCls(), 1);
Array.set(columns, 0, columnField1.getObject());
// 调用limit(5)方法
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExampleSelective", tbExample.getObject(), columns);
Assert.assertEquals(sql, "select field1 from tb limit 5");
// 调用limit(1, 5)方法
tbExample.invoke("limit", 1, 5);
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExampleSelective", tbExample.getObject(), columns);
Assert.assertEquals(sql, "select field1 from tb limit 1, 5");
// 执行一次看结果
List list = (List) tbMapper.invoke("selectByExampleSelective", tbExample.getObject(), columns);
Assert.assertEquals(list.size(), 5);
}
});
}
}
@@ -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.LimitPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>