因为在mybatis-config.xml文件中< mappers >标签中可能有多个< mapper >标签,即多xxxMapper.xml文件,所以我们需要将它们一一解析,这里我们可以准备一个list集合,用来存这些文件的resource路径,然后再一一根据路径解析文件。代码如下:
List<String> sqlMapperPathList = new ArrayList<>();
List<Node> nodes = document.selectNodes("//mapper");//双斜线的作用是从文件的任意位置找mapper一个斜线是从根标签开始寻找
nodes.forEach(node ->{
Element mapper = (Element) node;
String resource = mapper.attributeValue("resource");
sqlMapperPathList.add(resource);
});
Map<String,MappedStatement> mappedStatements = getMappedStatement(sqlMapperPathList);
为了代码的简洁,最后一行是将该集合传给了一个方法,在该方法中进行文件的解析,最后直接返回符合要求的结果集。
在解析的时候可以看着Mapper文件进行参考
方法代码如下:
/**
* 解析所有的sqlMapper.xml文件,然后构建Map集合
* @param sqlMapperPathList
* @return
*/
private Map<String, MappedStatement> getMappedStatement(List<String> sqlMapperPathList) {
Map<String, MappedStatement> mappedStatements = new HashMap<>();
sqlMapperPathList.forEach(mapperPath->{//遍历每一个路径,然后挨个解析
try {
SAXReader reader = new SAXReader();
Document document = reader.read(Resources.getResourceAsStream(mapperPath));
Element mapper = (Element) document.selectSingleNode("mapper");
String namespace = mapper.attributeValue("namespace");
List<Element> elements = mapper.elements();
elements.forEach(element -> {
String id = element.attributeValue("id");
String sqlId = namespace + '.' +id;//命名空间加id唯一确定一个命令标签
String resultType = element.attributeValue("resultType");
String sql = element.getTextTrim();
MappedStatement mappedStatement = new MappedStatement(sql, resultType);
mappedStatements.put(sqlId,mappedStatement);
});
} catch (Exception e) {
e.printStackTrace();
}
});
return mappedStatements;
}
到这里sqlSessionFactory对象创建的参数就已经准备完毕了,接下来就是测试功能。
测试代码如下
测试结果