最近公司要發展海外項目,因此要將現有的系統所有平移過去,另外數據庫也要從原來的Oracle
變爲Mysql
。公司的數據庫交互層面使用的是Mybatis
,而Oracle
與Mysql
也有一些語法上的不一樣。因此在項目中的Sql要改動,可是多個項目中涉及到的Sql很是多,若是僅憑人工一條一條辨別的話,工做量有點大。因此就萌發出了直接將數據源變爲Mysql,利用反射批量執行Mapper中的方法,而後若是有參數的話,就設置爲默認的初始值,而後記錄下來成功的數據和失敗的數據,這樣就能夠根據失敗緣由進行修改。可以節省很大的時間。java
整體思路就三步mysql
AutoTestMapper autoTestMapper = new AutoTestMapper("存放Mapper全路徑名"); autoTestMapper.openSqlSession(sqlSessionFactory);
在構造函數中傳入全路徑名後,進行解析,解析出包名和全部的文件名並存儲起來git
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
參數github
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()
方法了sql
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; }
這裏面完成爲參數賦初始值,和執行的邏輯。數據庫
自動測試Mapper除了傳參爲List和Set,其他都能測到。在xml中全部的if條件都會拼接到。mybatis
AutoTestMapper
拷貝到測試模塊中。如圖所示AutoTestMapper
文件存放在githubapp
resources
模塊中加入mybatis-config.xml
文件,如圖所示mybatis-config.xml
內容以下函數
<!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>
compile files('../lib/mybatis-3.5.0-hupengfeiTest.jar')此處路徑填寫相對路徑單元測試
若是目錄結構以下,那麼就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
若是目錄結構以下,那麼就compile files('../lib/mybatis-3.5.0-hupengfeiTest.jar')
-lib -- mybatis-3.5.0-hupengfeiTest.jar -service -- build.gradle
@RunWith(SpringJUnit4ClassRunner.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文件夾的全路徑名); //執行測試方法 autoTestMapper.openSqlSession(sqlSessionFactory); } }
就會在控制檯中打印出執行失敗的Mapper以及其緣由。以下圖所示