溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何批量測試Mybatis項目中SQL是否正確

發(fā)布時間:2020-06-26 20:37:36 來源:網(wǎng)絡(luò) 閱讀:1997 作者:Java_老男孩 欄目:編程語言

去Oracle行動

最近公司要發(fā)展海外項目,所以要將現(xiàn)有的系統(tǒng)全部平移過去,另外數(shù)據(jù)庫也要從原來的Oracle變?yōu)?a title="Mysql" target="_blank" href="http://www.kemok4.com/mysql/">Mysql。公司的數(shù)據(jù)庫交互層面使用的是Mybatis,而Oracle與Mysql也有一些語法上的不同。所以在項目中的Sql要改動,但是多個項目中涉及到的Sql非常多,如果僅憑人工一條一條辨別的話,工作量有點大。

所以就萌發(fā)出了直接將數(shù)據(jù)源變?yōu)镸ysql,利用反射批量執(zhí)行Mapper中的方法,然后如果有參數(shù)的話,就設(shè)置為默認(rèn)的初始值,然后記錄下來成功的數(shù)據(jù)和失敗的數(shù)據(jù),這樣就可以根據(jù)失敗原因進行修改。能夠節(jié)省很大的時間。

執(zhí)行效果

如何批量測試Mybatis項目中SQL是否正確

代碼介紹

總體思路就三步

  • 通過反射獲得要執(zhí)行的Mapper類的所有方法

  • 獲得方法中的參數(shù),并賦值

  • 執(zhí)行
AutoTestMapper autoTestMapper = new AutoTestMapper("存放Mapper全路徑名");
autoTestMapper.openSqlSession(sqlSessionFactory);

在構(gòu)造函數(shù)中傳入全路徑名后,進行解析,解析出包名和所有的文件名并存儲起來

    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;
    }

然后調(diào)用openSqlSession的方法,傳入SqlSessionFactory參數(shù)

        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);
            //反射執(zhí)行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<>();
        //給參數(shù)賦初始值
        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;
    }

這里面完成為參數(shù)賦初始值,和執(zhí)行的邏輯。

使用說明

自動測試Mapper除了傳參為List和Set,其余都能測到。在xml中所有的if條件都會拼接到。

將AutoTestMapper拷貝到測試模塊中。如圖所示

如何批量測試Mybatis項目中SQL是否正確

在resources模塊中加入mybatis-config.xml文件,如圖所示

如何批量測試Mybatis項目中SQL是否正確

mybatis-config.xml內(nèi)容如下

<!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="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="連接地址"/>
                <property name="username" value="賬號"/>
                <property name="password" value="密碼"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

在根目錄創(chuàng)建lib文件夾,并將測試的Mybatis版本放入其中,并在Gradle中引入此包

compile files('../lib/mybatis-3.5.0-hupengfeiTest.jar')此處路徑填寫相對路徑

如果目錄結(jié)構(gòu)如下,那么就compile files('lib/mybatis-3.5.0-hupengfeiTest.jar')

mybatis-3.5.0-hupengfeiTest.jar在github下面的lib目錄中

-lib
    -- mybatis-3.5.0-hupengfeiTest.jar
-build.gradle

如果目錄結(jié)構(gòu)如下,那么就compile files('../lib/mybatis-3.5.0-hupengfeiTest.jar')

-lib
    -- mybatis-3.5.0-hupengfeiTest.jar
-service
    -- build.gradle

如何批量測試Mybatis項目中SQL是否正確

在單元測試中編寫代碼,進行測試

@RunWith(SpringJUnit4Cla***unner.class)
@SpringBootTest(classes = { AirApplication.class })//此處AirApplication.class為項目中的啟動類,自行修改
public class TestMapper {

    @Test
    public void testCeshi()
            throws IllegalAccessException, IntrospectionException, InvocationTargetException, NoSuchMethodException,
            InstantiationException, IOException, ClassNotFoundException {
        //讀取Mybatis配置
        Reader resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
        //生成SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
        resourceAsReader.close();
        AutoTestMapper autoTestMapper = new AutoTestMapper(存放Mapper的Java文件夾的全路徑名);
        //執(zhí)行測試方法
        autoTestMapper.openSqlSession(sqlSessionFactory);
    }
}

就會在控制臺中打印出執(zhí)行失敗的Mapper以及其原因。如下圖所示

如何批量測試Mybatis項目中SQL是否正確

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI