自定义ORM(mybatis)源码(二)-解析mapper.xml
模仿mybatis
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<datasource>
<property key="driverName" value="com.mysql.cj.jdbc.Driver"></property>
<property key="url" value="jdbc:mysql://localhost:3306"></property>
<property key="username" value="test"></property>
<property key="password" value="test"></property>
</datasource>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</config>
这里解析 mappers 节点下的UserMapper.xml
XmlMapperParser
继承 BaseXmlParser
public class XmlMapperParser extends BaseXmlParser {
private Document document;
public XmlMapperParser(InputStream inputStream, Properties properties, Configuration configuration) {
super(configuration);
this.document = createDocument(new InputSource(inputStream));
}
@Override
public Configuration parse() {
try {
Configuration configuration = getConfiguration();
XNodeParser xNodeParser = new XNodeParser(document);
//解析 namespace
Node mapper = xNodeParser.getNodeObject("mapper");
String namespace = XNodeParser.getAttributeValue(mapper, "namespace");
Class<?> mapperClz = Class.forName(namespace);
//解析 sql-map
extractSelectNode(configuration, xNodeParser, namespace);
//增加mapper
configuration.addMapper(mapperClz);
return getConfiguration();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void extractSelectNode(Configuration configuration, XNodeParser xNodeParser, String namespace) throws XPathExpressionException {
NodeList nodeList = xNodeParser.getNodeList("mapper//select");
for (int i = 0; i < nodeList.getLength(); i++) {
Node select = nodeList.item(i);
MappedStatement stmt = new MappedStatement();
stmt.setNamespace(namespace);
stmt.setCommand("select");
//解析 resultType
extractResultMapping(namespace, select, stmt);
//解析sql
stmt.addBoundSql(new BoundSql(select.getTextContent()));
configuration.addMappedStatement(stmt);
}
}
private static void extractResultMapping(String namespace, Node select, MappedStatement stmt) {
String id = XNodeParser.getAttributeValue(select, "id");
stmt.setFullId(namespace.concat(".").concat(id));
String resultType = XNodeParser.getAttributeValue(select, "resultType");
Class<?> aClass;
try {
aClass = Class.forName(resultType);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
stmt.addResultMapping(new ResultMapping(id,aClass));
}
}
将解析的结果放在 Configuration中, 并且在 MapperRegistry 中创建 代理对象