Commit 51b812a5 authored by hewei's avatar hewei

插件SelectSelectivePlugin测试用例

parent 02e0367d
/*
* 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;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/29 13:29
* ---------------------------------------------------------------------------
*/
public class CommentPluginTest {
}
/*
* 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;
import com.itfsw.mybatis.generator.plugins.tools.AbstractShellCallback;
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
import com.itfsw.mybatis.generator.plugins.tools.ObjectUtil;
import com.itfsw.mybatis.generator.plugins.tools.SqlHelper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import java.io.IOException;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/29 13:34
* ---------------------------------------------------------------------------
*/
public class SelectSelectivePluginTest {
private DBHelper helper;
/**
* 初始化
* @throws IOException
* @throws SQLException
*/
@Before
public void init() throws IOException, SQLException {
helper = DBHelper.getHelper("scripts/SelectSelectivePlugin/init.sql");
}
/**
* 测试生成的方法
* @throws Exception
*/
@Test
public void testSelectByExampleSelective() throws Exception {
List<String> warnings = new ArrayList<>();
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(Resources.getResourceAsStream("scripts/SelectSelectivePlugin/mybatis-generator.xml"));
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, new AbstractShellCallback(true) {
@Override
public void reloadProject(ClassLoader loader) {
SqlSession sqlSession = null;
try {
// 1. 测试sql
sqlSession = helper.getSqlSession();
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass("com.itfsw.mybatis.generator.plugins.dao.TbMapper")));
ObjectUtil tbExample = new ObjectUtil(loader, "com.itfsw.mybatis.generator.plugins.dao.model.TbExample");
ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria"));
criteria.invoke("andIdLessThan", 100);
tbExample.set("orderByClause", "field2 asc");
ObjectUtil columnField1 = new ObjectUtil(loader, "com.itfsw.mybatis.generator.plugins.dao.model.Tb$Column#field1");
// java 动态参数不能有两个会冲突,最后一个封装成Array!!!必须使用反射创建指定类型数组,不然调用invoke对了可变参数会检查类型!
Object columns1 = Array.newInstance(columnField1.getCls(), 1);
Array.set(columns1, 0, columnField1.getObject());
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExampleSelective", tbExample.getObject(), columns1);
Assert.assertEquals(sql, "select field1 from tb order by field2 asc");
ObjectUtil columnField2 = new ObjectUtil(loader, "com.itfsw.mybatis.generator.plugins.dao.model.Tb$Column#field2");
Object columns2 = Array.newInstance(columnField1.getCls(), 2);
Array.set(columns2, 0, columnField1.getObject());
Array.set(columns2, 1, columnField2.getObject());
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExampleSelective", tbExample.getObject(), columns2);
Assert.assertEquals(sql, "select field1 , field2 from tb order by field2 asc");
// 2. 执行sql
List list = (List) tbMapper.invokeVarArgs("selectByExampleSelective", tbExample.getObject(), columns1);
Assert.assertEquals(list.size(), 3);
int index = 0;
for (Object obj : list) {
ObjectUtil objectUtil = new ObjectUtil(obj);
// 没有查询这两个字段
if (objectUtil.get("id") != null || objectUtil.get("field2") != null) {
Assert.assertTrue(false);
}
if (index == 0) {
Assert.assertEquals(objectUtil.get("field1"), "fd1");
} else if (index == 1) {
Assert.assertNull(objectUtil.get("field1"));
} else {
Assert.assertEquals(objectUtil.get("field1"), "fd3");
}
index++;
}
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
} finally {
sqlSession.close();
}
}
}, warnings);
myBatisGenerator.generate(null, null, null, true);
}
@AfterClass
public static void clean() {
// DBHelper.reset();
}
}
...@@ -19,7 +19,6 @@ package com.itfsw.mybatis.generator.plugins.tools; ...@@ -19,7 +19,6 @@ package com.itfsw.mybatis.generator.plugins.tools;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/** /**
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
...@@ -122,7 +121,6 @@ public class ObjectUtil { ...@@ -122,7 +121,6 @@ public class ObjectUtil {
if (method.getName().equals(methodName) && method.getParameterTypes().length == args.length) { if (method.getName().equals(methodName) && method.getParameterTypes().length == args.length) {
boolean flag = true; boolean flag = true;
Class[] parameterTypes = method.getParameterTypes(); Class[] parameterTypes = method.getParameterTypes();
Parameter[] pps = method.getParameters();
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
if (!(parameterTypes[i].isAssignableFrom(args[i].getClass()))) { if (!(parameterTypes[i].isAssignableFrom(args[i].getClass()))) {
flag = false; flag = false;
......
...@@ -19,6 +19,10 @@ ...@@ -19,6 +19,10 @@
<configuration> <configuration>
<properties resource="db.properties" /> <properties resource="db.properties" />
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
<!-- 配置环境,制定数据库连接信息 --> <!-- 配置环境,制定数据库连接信息 -->
<environments default="test"> <environments default="test">
<environment id="test"> <environment id="test">
......
/*
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-06-30 11:15:22
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb
-- ----------------------------
INSERT INTO `tb` VALUES ('1', 'fd1', null);
INSERT INTO `tb` VALUES ('2', null, '2');
INSERT INTO `tb` VALUES ('3', 'fd3', '3');
-- ----------------------------
-- Table structure for tb_blobs
-- ----------------------------
DROP TABLE IF EXISTS `tb_blobs`;
CREATE TABLE `tb_blobs` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL,
`field2` longtext COMMENT '注释2',
`field3` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_blobs
-- ----------------------------
-- ----------------------------
-- Table structure for tb_keys
-- ----------------------------
DROP TABLE IF EXISTS `tb_keys`;
CREATE TABLE `tb_keys` (
`key1` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`key2` varchar(255) NOT NULL,
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`key1`,`key2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_keys
-- ----------------------------
-- ----------------------------
-- Table structure for tb_single_blob
-- ----------------------------
DROP TABLE IF EXISTS `tb_single_blob`;
CREATE TABLE `tb_single_blob` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` longtext COMMENT '注释2',
`field2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_single_blob
-- ----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<!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">
<!-- 插件 -->
<!-- Select Selective插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin"/>
<!-- 数据Model属性对应Column获取插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!-- 查询单条数据插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${db.driver}" connectionURL="${db.url}" userId="${db.username}" password="${db.password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.itfsw.mybatis.generator.plugins.dao.model" targetProject="src/test/java">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="com.itfsw.mybatis.generator.plugins.dao" targetProject="src/test/java" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.itfsw.mybatis.generator.plugins.dao" targetProject="src/test/java" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys" />
<table tableName="tb_single_blob">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_blobs">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
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