批量测试Mybatis项目中Sql是否正确

栏目: Java · 发布时间: 7年前

内容简介:最近公司要发展海外项目,所以要将现有的系统全部平移过去,另外数据库也要从原来的总体思路就三步在构造函数中传入全路径名后,进行解析,解析出包名和所有的文件名并存储起来

最近公司要发展海外项目,所以要将现有的系统全部平移过去,另外数据库也要从原来的 Oracle 变为 Mysql 。公司的数据库交互层面使用的是 Mybatis ,而 OracleMysql 也有一些语法上的不同。所以在项目中的 Sql 要改动,但是多个项目中涉及到的Sql非常多,如果仅凭人工一条一条辨别的话,工作量有点大。所以就萌发出了直接将数据源变为Mysql,利用反射批量执行Mapper中的方法,然后如果有参数的话,就设置为默认的初始值,然后记录下来成功的数据和失败的数据,这样就可以根据失败原因进行修改。能够节省很大的时间。

执行效果

批量测试Mybatis项目中Sql是否正确

代码介绍

总体思路就三步

  1. 通过反射获得要执行的Mapper类的所有方法
  2. 获得方法中的参数,并赋值
  3. 执行
AutoTestMapper autoTestMapper = new AutoTestMapper("存放Mapper全路径名");
autoTestMapper.openSqlSession(sqlSessionFactory);

复制代码

在构造函数中传入全路径名后,进行解析,解析出包名和所有的文件名并存储起来

public AutoTestMapper(String path) throws IOException, ClassNotFoundException {
        String mapperContent = getFileContent(path);
        String pathPattern = "import [a-z,A-Z,/.]+;";
        String[] pathArr = matchMethod(pathPattern, mapperContent).split(";");
        for (int i = 0; i < pathArr.length; i++) {
            pathArr[i] = pathArr[i].replaceAll("import ", "");
            Class cls = Class.forName(pathArr[i]);
            if (!cls.isInterface()) {
                TYPE_ARRAY.add(cls);
            }
        }
        //获得全路径名的前缀
        String packPattern = "package [a-z,A-Z,/.]+;";
        String[] packPathArr = matchMethod(packPattern, mapperContent).split(";");
        String packPath = packPathArr[0].replaceAll("package ", "").replaceAll(";", "");
        this.PACK_PATH = packPath;
    }
复制代码

然后调用 openSqlSession 的方法,传入 SqlSessionFactory 参数

List<Map<Class, Object>> list = new ArrayList<>();
        List<String> invokeSuccess = new ArrayList<>();
        List<String> invokeFail = new ArrayList<>();
        for (String fileName : FILE_NAME) {
            Class cls = Class.forName(PACK_PATH + "." + fileName);
            //添加Mapper
            if (!sqlSessionFactory.getConfiguration().hasMapper(cls)){
                sqlSessionFactory.getConfiguration().addMapper(cls);
            }
            //获得Mapper
            Object mapper = sqlSessionFactory.openSession().getMapper(cls);
            //反射执行Mapper的方法
            Map<String, List<String>> resultMap = autoTestInvoke(cls, mapper);
            invokeSuccess.addAll(resultMap.get(SUCCESS_FLG));
            invokeFail.addAll(resultMap.get(FAIL_FLG));
        }

复制代码

然后通过Mybatyis提供的方法 getMapper() 传入类名获得所要Mapper类。核心方法就是 autoTestInvoke() 方法了

private Map<String, List<String>> autoTestInvoke(Class c, Object o)
     {
        Method[] declaredMethods = c.getDeclaredMethods();
        String fileName = c.getName().substring(c.getName().lastIndexOf("."));
        List<String> invokeSuccess = new ArrayList<>();
        List<String> invokeFail = new ArrayList<>();
        Map<String, List<String>> resultMap = new HashMap<>();
        //给参数赋初始值
        for (Method method : declaredMethods) {
            List<Object> list = new ArrayList<>();
            for (Class cls : method.getParameterTypes()) {
                Object par = new Object();
                if (TYPE_ARRAY.contains(cls)) {
                    if (cls.equals(String.class)) {
                        par = "1";
                    } else {
                        try {
                            par = cls.newInstance();
                            assignment(cls, par);
                        } catch (InstantiationException e) {
                            if (cls.isPrimitive()) {
                                cls = primitiveClazz.get(cls.getName());
                            }
                            try {
                                par = cls.getDeclaredConstructor(String.class).newInstance("1");

                            }catch (NoSuchMethodException e1){
                                System.out.println(cls.getName()+e);
                            }
                        }
                    }
                }else if ("java.util.Map".equals(cls.getName())){
                    par = getMapData(c.getName()+"."+method.getName());
                }
                list.add(par);
            }
            try {
                method.invoke(o, list.toArray());
                invokeSuccess.add("Success: " + fileName + "." + method.getName());
            } catch (Exception e) {
                invokeFail.add("Error:" + method.getName() + "   Error Info:" + e);
            }
        }
        resultMap.put(SUCCESS_FLG, invokeSuccess);
        resultMap.put(FAIL_FLG, invokeFail);
        return resultMap;
    }

复制代码

这里面完成为参数赋初始值,和执行的逻辑。

使用说明

导入Jar包

Maven

<dependency>
  <groupId>com.github.modouxiansheng</groupId>
  <artifactId>convenientUtil</artifactId>
  <version>1.3-release</version>
</dependency>

复制代码

Gradle

compile 'com.github.modouxiansheng:convenientUtil:1.1-release'

复制代码

创建 mybatis-config.xml 文件

在项目的resource文件夹下创建mybatis-config.xml文件,里面内容如下,里面value值为想要测的数据库的连接信息

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value=""/>
                <property name="url" value=""/>
                <property name="username" value=""/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
</configuration>

复制代码

在测试类中编写代码

在测试类中编写如下代码

Reader resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
resourceAsReader.close();
AutoTestMapper autoTestMapper = new AutoTestMapper("想要测试的Mapper文件夹全路径名");
autoTestMapper.openSqlSession(sqlSessionFactory); 
复制代码

查看输出的信息

然后会打印出执行成功的Sql,执行失败的Sql。如果失败的话会有原因。

Success: TSesSetManualMapper.updateFlgdelAutoInTimePay
Success: TSesSetManualMapper.getAutoSetManualOrdListCount
Success: TSesSetManualMapper.updateAutoSetManualOrd
Success: TSesSetManualMapper.queryAutoSetManualOrdDetail
Success: TSesSetManualMapper.querySetManualOrdListCount
Success: ShortMessageMapper.queryPayInsSmInfo
-------------------
|Error: |TSesSetManualMapper.queryAutoSetManualOrdList|  Every derived table must have its own alias|
|Error: |TSesSetManualMapper.querySetManualOrdList|  Every derived table must have its own alias|
复制代码

这样就能够根据错误信息进行更改了。

github地址: github.com/modouxiansh…


以上所述就是小编给大家介绍的《批量测试Mybatis项目中Sql是否正确》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript and Ajax for the Web, Sixth Edition

JavaScript and Ajax for the Web, Sixth Edition

Tom Negrino、Dori Smith / Peachpit Press / August 28, 2006 / $24.99

Book Description Need to learn JavaScript fast? This best-selling reference’s visual format and step-by-step, task-based instructions will have you up and running with JavaScript in no time. In thi......一起来看看 《JavaScript and Ajax for the Web, Sixth Edition》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具