Commit ae31f59d authored by hewei's avatar hewei

构建测试体系

parent eb2f231b
...@@ -57,7 +57,25 @@ ...@@ -57,7 +57,25 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>3.8.1</version> <version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
......
/*
* 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.DBHelper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/26 17:19
* ---------------------------------------------------------------------------
*/
public class DBHelperTest {
/**
* 测试 getSqlSession
*
* @throws IOException
* @throws SQLException
*/
@Test
public void testGetSqlSession() throws IOException, SQLException {
DBHelper helper = DBHelper.getHelper("scripts/test_init.sql");
SqlSession sqlSession = helper.getSqlSession();
Connection connection = sqlSession.getConnection();
Statement statement = connection.createStatement();
// 执行查询
statement.execute("SELECT COUNT(*) as total FROM tb");
ResultSet resultSet = statement.getResultSet();
resultSet.first();
Assert.assertEquals(resultSet.getInt("total"), 4);
statement.close();
connection.close();
sqlSession.close();
}
}
/*
* 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.tools;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/26 16:52
* ---------------------------------------------------------------------------
*/
public class DBHelper {
private static final String MYBATIS_CONFIG = "mybatis-config.xml"; // 配置文件
private static DBHelper helper; // helper
/**
* 构造函数
*/
private DBHelper() {
}
/**
* 获取数据库操作工具
*
* @param initSql
* @return
*/
public static DBHelper getHelper(String initSql) throws IOException, SQLException {
if (helper == null){
helper = new DBHelper();
helper.initDB(initSql);
}
return helper;
}
/**
* 获取SqlSession
*
* @return
* @throws IOException
*/
public SqlSession getSqlSession() throws IOException {
InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
inputStream.close();
return sqlSessionFactory.openSession(true);
}
/**
* 初始化数据库
*
* @param initSql
* @throws IOException
* @throws SQLException
*/
private void initDB(String initSql) throws IOException, SQLException {
SqlSession sqlSession = this.getSqlSession();
Connection connection = sqlSession.getConnection();
Statement statement = connection.createStatement();
// 获取建表和初始化sql
InputStream inputStream = Resources.getResourceAsStream(initSql);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取sql语句执行
StringBuffer sb = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null){
sb.append(line).append("\n");
if (line.matches(".*;$")){
System.out.println(sb.toString());
statement.execute(sb.toString());
sb.setLength(0);
}
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
statement.close();
connection.close();
sqlSession.close();
}
}
/*
* 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.tools;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/26 15:42
* ---------------------------------------------------------------------------
*/
public class SqlHelper {
private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
/**
* 通过接口获取sql
* @param mapper
* @param methodName
* @param args
* @return
*/
public static String getMapperSql(Object mapper, String methodName, Object... args) {
MetaObject metaObject = SystemMetaObject.forObject(mapper);
SqlSession session = (SqlSession) metaObject.getValue("h.sqlSession");
Class mapperInterface = (Class) metaObject.getValue("h.mapperInterface");
String fullMethodName = mapperInterface.getCanonicalName() + "." + methodName;
if (args == null || args.length == 0) {
return getNamespaceSql(session, fullMethodName, null);
} else {
return getMapperSql(session, mapperInterface, methodName, args);
}
}
/**
* 通过Mapper方法名获取sql
* @param session
* @param fullMapperMethodName
* @param args
* @return
*/
public static String getMapperSql(SqlSession session, String fullMapperMethodName, Object... args) {
if (args == null || args.length == 0) {
return getNamespaceSql(session, fullMapperMethodName, null);
}
String methodName = fullMapperMethodName.substring(fullMapperMethodName.lastIndexOf('.') + 1);
Class mapperInterface = null;
try {
mapperInterface = Class.forName(fullMapperMethodName.substring(0, fullMapperMethodName.lastIndexOf('.')));
return getMapperSql(session, mapperInterface, methodName, args);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("参数" + fullMapperMethodName + "无效!");
}
}
/**
* 通过Mapper接口和方法名
* @param session
* @param mapperInterface
* @param methodName
* @param args
* @return
*/
public static String getMapperSql(SqlSession session, Class mapperInterface, String methodName, Object... args) {
String fullMapperMethodName = mapperInterface.getCanonicalName() + "." + methodName;
if (args == null || args.length == 0) {
return getNamespaceSql(session, fullMapperMethodName, null);
}
Method method = getDeclaredMethods(mapperInterface, methodName);
Map params = new HashMap();
final Class<?>[] argTypes = method.getParameterTypes();
for (int i = 0; i < argTypes.length; i++) {
if (!RowBounds.class.isAssignableFrom(argTypes[i]) && !ResultHandler.class.isAssignableFrom(argTypes[i])) {
String paramName = "param" + String.valueOf(params.size() + 1);
paramName = getParamNameFromAnnotation(method, i, paramName);
params.put(paramName, i >= args.length ? null : args[i]);
}
}
if (args != null && args.length == 1) {
Object _params = wrapCollection(args[0]);
if (_params instanceof Map) {
params.putAll((Map) _params);
}
}
return getNamespaceSql(session, fullMapperMethodName, params);
}
/**
* 通过命名空间方式获取sql
* @param session
* @param namespace
* @return
*/
public static String getNamespaceSql(SqlSession session, String namespace) {
return getNamespaceSql(session, namespace, null);
}
/**
* 通过命名空间方式获取sql
* @param session
* @param namespace
* @param params
* @return
*/
public static String getNamespaceSql(SqlSession session, String namespace, Object params) {
params = wrapCollection(params);
Configuration configuration = session.getConfiguration();
MappedStatement mappedStatement = configuration.getMappedStatement(namespace);
TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
BoundSql boundSql = mappedStatement.getBoundSql(params);
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql();
if (parameterMappings != null) {
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (params == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(params.getClass())) {
value = params;
} else {
MetaObject metaObject = configuration.newMetaObject(params);
value = metaObject.getValue(propertyName);
}
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
sql = replaceParameter(sql, value, jdbcType, parameterMapping.getJavaType());
}
}
}
return sql;
}
/**
* 根据类型替换参数
*
* 仅作为数字和字符串两种类型进行处理,需要特殊处理的可以继续完善这里
* @param sql
* @param value
* @param jdbcType
* @param javaType
* @return
*/
private static String replaceParameter(String sql, Object value, JdbcType jdbcType, Class javaType) {
String strValue = String.valueOf(value);
if (jdbcType != null) {
switch (jdbcType) {
//数字
case BIT:
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT:
case FLOAT:
case REAL:
case DOUBLE:
case NUMERIC:
case DECIMAL:
break;
//日期
case DATE:
case TIME:
case TIMESTAMP:
//其他,包含字符串和其他特殊类型
default:
strValue = "'" + strValue + "'";
}
} else if (Number.class.isAssignableFrom(javaType)) {
//不加单引号
} else {
strValue = "'" + strValue + "'";
}
return sql.replaceFirst("\\?", strValue);
}
/**
* 获取指定的方法
* @param clazz
* @param methodName
* @return
*/
private static Method getDeclaredMethods(Class clazz, String methodName) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
return method;
}
}
throw new IllegalArgumentException("方法" + methodName + "不存在!");
}
/**
* 获取参数注解名
* @param method
* @param i
* @param paramName
* @return
*/
private static String getParamNameFromAnnotation(Method method, int i, String paramName) {
final Object[] paramAnnos = method.getParameterAnnotations()[i];
for (Object paramAnno : paramAnnos) {
if (paramAnno instanceof Param) {
paramName = ((Param) paramAnno).value();
}
}
return paramName;
}
/**
* 简单包装参数
* @param object
* @return
*/
private static Object wrapCollection(final Object object) {
if (object instanceof List) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", object);
return map;
} else if (object != null && object.getClass().isArray()) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("array", object);
return map;
}
return object;
}
}
<?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 configuration PUBLIC "-//mybatis.org//DTDSQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置环境,制定数据库连接信息 -->
<environments default="test">
<environment id="test">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis-generator-plugin?characterEncoding=UTF-8&amp;allowMultiQueries=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- Mapper扫描包,必须同目录同名称下-->
<package name="com.itfsw.mybatis.generator.plugins.dao"/>
</mappers>
</configuration>
\ No newline at end of file
/*
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-26 17:30:13
*/
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',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of tb
-- ----------------------------
INSERT INTO `tb` VALUES ('1', 'f1');
INSERT INTO `tb` VALUES ('2', 'f2');
INSERT INTO `tb` VALUES ('3', 'f3');
INSERT INTO `tb` VALUES ('4', 'f4');
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