模仿与学习MyBatis - 1.3 xml配置的解析

本文收录于模仿与学习MyBatis系列


简述

在前一章《模仿与学习MyBatis - 1.2 DataSource与Session》中实现了一个基本的DataSource与Session。但是DataSource的值需要在Java代码中设置的,不是很利于更改配置。所以在这一篇,新增一个XMLConfigBuilder类,能读取xml文件并生成一个DataSource。
最终产生的是一个Java Maven项目,代码存在github


配置格式

既然要使用xml文件来配置一个DataSource,那么我们肯定要有一个格式标准,方便XMLConfigBuilder将按此格式读取xml文件。由于暂时配置内容较少,所以先简单的定义一下:

<?xml version="1.0" encoding="UTF-8"?>
<database>
    <property name="driverClassName">com.mysql.jdbc.Driver</property>
    <property name="url">jdbc:mysql://localhost:3306/webserver?useUnicode=true&amp;characterEncoding=utf8</property>
    <property name="username">root</property>
    <property name="password">123456</property>
</database>

dom4j

既然xml文件已经有了,我们怎么解析它呢?我选择的是dom4j这个包,能读取每一个结点的标签、属性、孩子等,而且使用较为简单,只需要输入流或文件即可解析。如果是普通java项目,需要上网查找dom4j的jar包导入,而如果是maven项目,在pom.xml中加入依赖项即可:

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
// 代码示例
// InputStream in;
SAXReader reader = new SAXReader();
Document document = reader.read(in);
Element root = document.getRootElement();
String tagName = root.getName();    // 标签名
for (Object item : root.elements("xxx")) {
    // e表示root的标签名为xxx的孩子
    Element e = (Element) item;
}

XMLConfigure:获取配置信息

有了如上知识,已经足以解析一个xml文件了。那么新建一个config包,在其中加入一个类XMLConfigBuilder,利用dom4j读取分析及生成DataSource。 以下是读取过程(一般可以通过以下方式获取loader,以读取项目目录下的文件):

private static ClassLoader loader = ClassLoader.getSystemClassLoader();

public static DataSource build(String resource)
{
    try {
        InputStream stream = loader.getResourceAsStream(resource);
        SAXReader reader = new SAXReader();
        Document document = reader.read(stream);
        Element root = document.getRootElement();
        // Element代入,生成DataSource
        return evalDataSource(root);
    } catch (Exception e) {
        throw new RuntimeException("error occured while evaling xml " + resource);
    }
}

接下来是对内容的解析:

public static DataSource evalDataSource(Element node) throws ClassNotFoundException 
{
    if (!node.getName().equals("database")) {
        throw new RuntimeException("root should be <database>");
    }
    String driverClassName = null;
    String url = null;
    String username = null;
    String password = null;
    for (Object item : node.elements("property")) {
        Element i = (Element) item;         
        String value = getValue(i);
        String name = i.attributeValue("name");
        if (name == null || value == null) 
            throw new RuntimeException("[database]: <property> should contain name and value");

        switch (name) {
            case "url" : url = value; break;
            case "username" : username = value; break;
            case "password" : password = value; break;
            case "driverClassName" : driverClassName = value; break; 
            default : throw new RuntimeException("[database]: <property> unknown name"); 
        }
    }
    return new VDataSource(driverClassName, url, username, password);
}

最后试一段测试代码:

DataSource ds = XMLConfigBuilder.build("config.xml");
Session session = new VSession(data);
session.exec("select * from article where id<30");

输出结果如下,与预期一致:

--------------------print--------------------
id=1
title=欢迎来到自由茶社
brief=这里是大门的入口
content=这里是大门的入口
father_id=0
author_name=me
create_time=2016-11-16 23:44:36.0
modify_time=2016-12-06 00:41:07.0

id=29
title=第一章
brief=随便打的内容
content=随便打的内容
father_id=1
author_name=me
create_time=2016-11-16 23:45:20.0
modify_time=2016-11-16 23:45:20.0

结语

其实可以发现,这里的XMLConfigBuilder,只是负责读取DataSource的配置并返回一个设置好值的DataSource。其它需要配置的,如别名、事务等等配置,也是同理的。
下一章,将介绍SessionFactory的意义,以及借由XMLConfigBuilder实现一个基本的SessionFactory类。

下一篇:模仿与学习MyBatis - 1.4 SessionFactory与Session

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值