封装sqlSessionFactory对象最后一步,解析xxxMapper.xml文件,并且测试创建对象

文章讲述了如何处理mybatis-config.xml文件中的多个mapper标签,通过创建list存储资源路径,使用SAXReader解析每个mapper文件,构建MappedStatement并存储到map中,以namespace和id作为键值。
摘要由CSDN通过智能技术生成

因为在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对象创建的参数就已经准备完毕了,接下来就是测试功能。

测试代码如下
在这里插入图片描述
测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只呆小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值