批量測試Mybatis專案中Sql是否正確
最近公司要發展海外專案,所以要將現有的系統全部平移過去,另外資料庫也要從原來的 Oracle
變為 Mysql
。公司的資料庫互動層面使用的是 Mybatis
,而 Oracle
與 Mysql
也有一些語法上的不同。所以在專案中的Sql要改動,但是多個專案中涉及到的Sql非常多,如果僅憑人工一條一條辨別的話,工作量有點大。所以就萌發出了直接將資料來源變為Mysql,利用反射批量執行Mapper中的方法,然後如果有引數的話,就設定為預設的初始值,然後記錄下來成功的資料和失敗的資料,這樣就可以根據失敗原因進行修改。能夠節省很大的時間。
執行效果

程式碼介紹
總體思路就三步
- 通過反射獲得要執行的Mapper類的所有方法
- 獲得方法中的引數,並賦值
- 執行
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包
<dependency> <groupId>com.github.modouxiansheng</groupId> <artifactId>convenientUtil</artifactId> <version>1.3-release</version> </dependency> 複製程式碼
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地址: ofollow,noindex">github.com/modouxiansh…