当前位置: 首页 > 图灵资讯 > 技术篇> 使用dom4j解析mybatis核心配置文件

使用dom4j解析mybatis核心配置文件

来源:图灵教育
时间:2023-06-02 09:26:28

1.代码32-34commtest代码.powernode.xml.testParseXMLByDom4jTest

package com.powernode.xml.test;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.Node;import org.dom4j.io.SAXReader;import org.junit.Test;import java.io.InputStream;import java.util.List;//使用dom4j分析mybatis核心配置文件   32public class ParseXMLByDom4jTest {    //分析CarMaperper.xml  34    @Test    public void testParseSqlMapperXML() throws Exception{        SAXReader reader = new SAXReader();        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("CarMapper.xml");        Document document = reader.read(is);        // namespace获取        String xpath = "/mapper";        Element mapper = (Element) document.selectSingleNode(xpath);        String namespace = mapper.attributeValue("namespace");        System.out.println(namespace);        // 在mapper节点下获取所有子节点        List elements = mapper.elements();        // 遍历        elements.forEach(element -> {            // 获取sqlid            String id = element.attributeValue("id");            System.out.println(id);            // resulttype获得            // 如果没有这个属性,“会自动返回”“会自动返回”null"            String resultType = element.attributeValue("resultType");             System.out.println(resultType);            // 获取标签中的sql语句(表示获取标签中的文本内容,并去除前后空白)            String sql = element.getTextTrim();            System.out.println(sql);                        // insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})            // insert into t_car values(null,?,?,?,?,?,?)            // jdbc包装了mybaits。早晚执行带早晚执行带sql语句。            // 转换            String newSql = sql.replaceAll(#\[0-9A]-Za-z___ "?");            System.out.println(newSql);        });    }    //使用dom4j分析mybatis核心配置文件   32    @Test    public void testParseMyBatisConfigXML() throws Exception{        // 创建SAXReader对象        SAXReader reader = new SAXReader();        // 获取输入流        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");        // 读XML文件,返回document对象。document对象是代表整个XML文件的文档对象。        Document document = reader.read(is);        //System.out.println(document);//        // 获取文件中的根标签///        Element rootElt = document.getRootElement();//        String rootEltName = rootElt.getName();//        System.out.println(根节点的名称:" + rootEltName);//        ///获得default默认环境id        // xpath匹配标签路径。XML文件中的元素可以快速定位。        // 以下xpath代表:从根部开始寻找configuration标签,然后找configuration标签        // environments的子标签        String xpath = "/configuration/environments";        // Element是Node类的子类,方法多,使用方便。        Element environments = (Element) document.selectSingleNode(xpath);        // 获取属性值        String defaultEnvironmentId = environments.attributeValue("default");        System.out.println(默认环境的id:" + defaultEnvironmentId);        // 获取特定的环境environmentent        xpath = "/configuration/environments/environment[@id='"+defaultEnvironmentId+"']";        //System.out.println(xpath);        Element environment = (Element) document.selectSingleNode(xpath);        // 33        // 在environment节点下获取transactionmanger节点(element)element()获取儿童节点的方法)        Element transactionManager = environment.element("transactionManager");        String transactionType = transactionManager.attributeValue("type");        System.out.println(”事务管理器的类型:" + transactionType);        // dataSource节点获得        Element dataSource = environment.element("dataSource");        String dataSourceType = dataSource.attributeValue("type");        System.out.println(”数据源类型:" + dataSourceType);        // dataSource节点获得下的所有子节点        List propertyElts = dataSource.elements();        // 遍历        propertyElts.forEach(propertyElt -> {            String name = propertyElt.attributeValue("name");            String value = propertyElt.attributeValue("value");            System.out.println(name + "=" + value);        });        // 获取所有mapper标签        // 不想从根开始,你想从任何位置获得所有的标签,xpath应该这样写        xpath = "//mapper";        List mappers = document.selectNodes(xpath);        // 遍历        mappers.forEach(mapper -> {            Element mapperElt = (Element) mapper;            String resource = mapperElt.attributeValue("resource");            System.out.println(resource);        });    }}

resources目录mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <environments default="powernodeDB">        <environment id="powernodeDB">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/powernode"/>                <property name="username" value="root"/>                <property name="password" value="lzl"/>            </dataSource>        </environment>        <!--这是mybatis的另一个环境,即连接到的数据库是另一个数据库mybatis-->        <environment id="mybatisDB">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>                <property name="username" value="root"/>                <property name="password" value="lzl"/>            </dataSource>        </environment>    </environments>    <mappers>        <!--resource属性自动从类的根路径下开始寻找资源。--resource属性自动从类的根路径下开始寻找资源。-->        <mapper resource="CarMapper.xml"/>    </mappers></configuration>

CarMappper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="car">    <insert id="insertCar">        insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})    </insert>    <select id="selectById" resultType="com.powernode.mybatis.pojo.Car">        select            id,car_num as carNum,brand,guide_price as guidePrice,            produce_time as produceTime,            car_type as carType        from            t_car        where            id = #{id}    </select></mapper>

pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.powernode</groupId>    <artifactId>course6</artifactId>    <version>1.0-SNAPSHOT</version>    <packaging>jar</packaging>    <!--依赖-->    <dependencies>        <!--依赖dom4j-->        <dependency>            <groupId>org.dom4j</groupId>            <artifactId>dom4j</artifactId>            <version>2.1.3</version>        </dependency>        <!--依赖jaxen-->        <dependency>            <groupId>jaxen</groupId>            <artifactId>jaxen</artifactId>            <version>1.2.0</version>        </dependency>        <!--依赖junit-->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.13.2</version>            <scope>test</scope>        </dependency>    </dependencies>    <properties>        <!--    jdk版本用于编译代码-->        <maven.compiler.source>1.8</maven.compiler.source>        <!--    使用jdk版本的操作程序-->        <maven.compiler.target>1.8</maven.compiler.target>    </properties></project>

使用dom4j解析mybatis核心配置文件_xml