MyBatis之xml配置的解析
admin
2024-03-08 08:14:54

转自:

MyBatis之xml配置的解析

下文笔者讲述Mybatis之xml配置解析的相关简介说明,如下所示
下文笔者讲述使用XMLConfigBuilder类
读取xml文件并生成一个DataSource
使用xml配置一个DataSource

xml格式如下所示:


com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=utf8root123456

dom4j

dom4j可用于读取每一个节点的标签、属性、子节点等
而且使用较为简单,只需要输入流或文件即可解析
例: 使用dom4j,先引入dom4j相应的jar包

dom4jdom4j1.6.1

编写相应的示例代码

// 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之获取配置信息

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代入,生成DataSourcereturn 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 ");}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]:  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]:  unknown name"); }}return new VDataSource(driverClassName, url, username, password);
}//测试代码
DataSource ds = XMLConfigBuilder.build("config.xml");
Session session = new VSession(data);
session.exec("select * from users where id<8");

相关内容

热门资讯

教师专享福利!北京这些景区免票... 新京报讯 据首都教育消息,教师节将至,北京多家景区为老师们准备了专属免票福利!这份优惠合集已整理好,...
黑茶,喝的是一种境界与健康 在专门用来喝黑茶的茶具“飘逸杯”里,黑茶茶汤看起来并不像“黑茶”这个名字那样黑黢黢的一团。 玻璃器皿...
上海旅游节大巡游花车阵容抢先看... 2026上海旅游节大巡游9月12日外滩启幕,21辆全新主题花车携手21支境内外表演方队联袂登场,邀你...
原创 8... 上周门诊来了位 62 岁的张阿姨,得糖尿病快五年了,平时管嘴特别严,糖果、点心、甜饮料一概不碰,连水...
原创 餐... 2026年9月8日晚,南京浦口区泰冯路29号,墨语江南·阿婆菜餐厅户外帐篷里,灯火温润,其间还天降喜...