mybatis xml文件热加载怎么实现

发布时间:2023-03-27 10:10:19 作者:iii
来源:亿速云 阅读:143

这篇文章主要介绍了mybatis xml文件热加载怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇mybatis xml文件热加载怎么实现文章都会有所收获,下面我们一起来看看吧。

一、xml 文件热加载实现原理

1.1 xml 文件怎么样解析

在Spring Boot + Mybatis的常规项目中,通过 org.mybatis.spring.SqlSessionFactoryBean 这个类的 buildSqlSessionFactory() 方法完成对 xml 文件的加载逻辑,这个方法只会在自动配置类 MybatisAutoConfiguration 初始化操作时进行调用。这里把 buildSqlSessionFactory() 方法中 xml 解析核心部分进行展示如下:

mybatis xml文件热加载怎么实现

通过 xmlMapperBuilder.parse() 方法解析 xml 文件各个节点,解析方法如下:

mybatis xml文件热加载怎么实现

简单来说,这个方法会解析 xml 文件中的 mapper|resultMap|cache|cache-ref|sql|select|insert|update|delete 等标签。将他们保存在 org.apache.ibatis.session.Configuration 类的对应属性中,如下展示:

mybatis xml文件热加载怎么实现

到这里,我们就知道了 Mybatis 对 xml 文件解析是通过 xmlMapperBuilder.parse() 方法完成并且只会在项目启动时加载 xml 文件。

1.2 实现思路

通过对上述 xml 解析逻辑进行分析,我们可以通过监听 xml 文件的修改,当监听到修改操作时,直接调用 xmlMapperBuilder.parse() 方法,将修改过后的 xml 文件进行重新解析,并替换内存中的对应属性以此完成热加载操作。这里也就引出了本文所讲的主角:mybatis-xmlreload-spring-boot-starter

二、mybatis-xmlreload-spring-boot-starter 登场

mybatis-xmlreload-spring-boot-starter 这个项目完成了博主上述的实现思路,使用技术如下:

2.1 核心代码

项目的结构如下:

mybatis xml文件热加载怎么实现

核心代码在 MybatisXmlReload 类中,代码展示:

/**
 * mybatis-xml-reload核心xml热加载逻辑
 */
public class MybatisXmlReload {
    private static final Logger logger = LoggerFactory.getLogger(MybatisXmlReload.class);
    /**
     * 是否启动以及xml路径的配置类
     */
    private MybatisXmlReloadProperties prop;
    /**
     * 获取项目中初始化完成的SqlSessionFactory列表,对多数据源进行处理
     */
    private List<SqlSessionFactory> sqlSessionFactories;
    public MybatisXmlReload(MybatisXmlReloadProperties prop, List<SqlSessionFactory> sqlSessionFactories) {
        this.prop = prop;
        this.sqlSessionFactories = sqlSessionFactories;
    }
    public void xmlReload() throws IOException {
        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        String CLASS_PATH_TARGET = File.separator + "target" + File.separator + "classes";
        String MAVEN_RESOURCES = "/src/main/resources";
        // 1. 解析项目所有xml路径,获取xml文件在target目录中的位置
        List<Resource> mapperLocationsTmp = Stream.of(Optional.of(prop.getMapperLocations()).orElse(new String[0]))
                .flatMap(location -> Stream.of(getResources(patternResolver, location))).toList();
        List<Resource> mapperLocations = new ArrayList<>(mapperLocationsTmp.size() * 2);
        Set<Path> locationPatternSet = new HashSet<>();
        // 2. 根据xml文件在target目录下的位置,进行路径替换找到该xml文件在resources目录下的位置
        for (Resource mapperLocation : mapperLocationsTmp) {
            mapperLocations.add(mapperLocation);
            String absolutePath = mapperLocation.getFile().getAbsolutePath();
            File tmpFile = new File(absolutePath.replace(CLASS_PATH_TARGET, MAVEN_RESOURCES));
            if (tmpFile.exists()) {
                locationPatternSet.add(Path.of(tmpFile.getParent()));
                FileSystemResource fileSystemResource = new FileSystemResource(tmpFile);
                mapperLocations.add(fileSystemResource);
            }
        }
        // 3. 对resources目录的xml文件修改进行监听
        List<Path> rootPaths = new ArrayList<>();
        rootPaths.addAll(locationPatternSet);
        DirectoryWatcher watcher = DirectoryWatcher.builder()
                .paths(rootPaths) // or use paths(directoriesToWatch)
                .listener(event -> {
                    switch (event.eventType()) {
                        case CREATE: /* file created */
                            break;
                        case MODIFY: /* file modified */
                            Path modifyPath = event.path();
                            String absolutePath = modifyPath.toFile().getAbsolutePath();
                            logger.info("mybatis xml file has changed:" + modifyPath);
                            // 4. 对多个数据源进行遍历,判断修改过的xml文件属于那个数据源
                            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
                                try {
                                    // 5. 获取Configuration对象
                                    Configuration targetConfiguration = sqlSessionFactory.getConfiguration();
                                    Class<?> tClass = targetConfiguration.getClass(), aClass = targetConfiguration.getClass();
                                    if (targetConfiguration.getClass().getSimpleName().equals("MybatisConfiguration")) {
                                        aClass = Configuration.class;
                                    }
                                    Set<String> loadedResources = (Set<String>) getFieldValue(targetConfiguration, aClass, "loadedResources");
                                    loadedResources.clear();
                                    Map<String, ResultMap> resultMaps = (Map<String, ResultMap>) getFieldValue(targetConfiguration, tClass, "resultMaps");
                                    Map<String, XNode> sqlFragmentsMaps = (Map<String, XNode>) getFieldValue(targetConfiguration, tClass, "sqlFragments");
                                    Map<String, MappedStatement> mappedStatementMaps = (Map<String, MappedStatement>) getFieldValue(targetConfiguration, tClass, "mappedStatements");
                                    // 6. 遍历xml文件
                                    for (Resource mapperLocation : mapperLocations) {
                                        // 7. 判断是否是被修改过的xml文件,否则跳过
                                        if (!absolutePath.equals(mapperLocation.getFile().getAbsolutePath())) {
                                            continue;
                                        }
                                        // 8. 重新解析xml文件,替换Configuration对象的相对应属性
                                        XPathParser parser = new XPathParser(mapperLocation.getInputStream(), true, targetConfiguration.getVariables(), new XMLMapperEntityResolver());
                                        XNode mapperXnode = parser.evalNode("/mapper");
                                        List<XNode> resultMapNodes = mapperXnode.evalNodes("/mapper/resultMap");
                                        String namespace = mapperXnode.getStringAttribute("namespace");
                                        for (XNode xNode : resultMapNodes) {
                                            String id = xNode.getStringAttribute("id", xNode.getValueBasedIdentifier());
                                            resultMaps.remove(namespace + "." + id);
                                        }
                                        List<XNode> sqlNodes = mapperXnode.evalNodes("/mapper/sql");
                                        for (XNode sqlNode : sqlNodes) {
                                            String id = sqlNode.getStringAttribute("id", sqlNode.getValueBasedIdentifier());
                                            sqlFragmentsMaps.remove(namespace + "." + id);
                                        }
                                        List<XNode> msNodes = mapperXnode.evalNodes("select|insert|update|delete");
                                        for (XNode msNode : msNodes) {
                                            String id = msNode.getStringAttribute("id", msNode.getValueBasedIdentifier());
                                            mappedStatementMaps.remove(namespace + "." + id);
                                        }
                                        try {
                                            // 9. 重新加载和解析被修改的 xml 文件
                                            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                                                    targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
                                            xmlMapperBuilder.parse();
                                        } catch (Exception e) {
                                            logger.error(e.getMessage(), e);
                                        }
                                        logger.info("Parsed mapper file: '" + mapperLocation + "'");
                                    }
                                } catch (Exception e) {
                                    logger.error(e.getMessage(), e);
                                }
                            }
                            break;
                        case DELETE: /* file deleted */
                            break;
                    }
                })
                .build();
        ThreadFactory threadFactory = r -> {
            Thread thread = new Thread(r);
            thread.setName("xml-reload");
            thread.setDaemon(true);
            return thread;
        };
        watcher.watchAsync(new ScheduledThreadPoolExecutor(1, threadFactory));
    }
    /**
     * 根据xml路径获取对应实际文件
     *
     * @param location 文件位置
     * @return Resource[]
     */
    private Resource[] getResources(PathMatchingResourcePatternResolver patternResolver, String location) {
        try {
            return patternResolver.getResources(location);
        } catch (IOException e) {
            return new Resource[0];
        }
    }
    /**
     * 根据反射获取 Configuration 对象中属性
     */
    private static Object getFieldValue(Configuration targetConfiguration, Class<?> aClass,
                                        String filed) throws NoSuchFieldException, IllegalAccessException {
        Field resultMapsField = aClass.getDeclaredField(filed);
        resultMapsField.setAccessible(true);
        return resultMapsField.get(targetConfiguration);
    }
}

代码执行逻辑:

2.2 安装方式

<dependency>
    <groupId>com.wayn</groupId>
    <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
    <version>3.0.3.m1</version>
</dependency>
<dependency>
    <groupId>com.wayn</groupId>
    <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
    <version>2.0.1.m1</version>
</dependency>

2.3 使用配置

Maven 项目写入mybatis-xmlreload-spring-boot-starter坐标后即可使用本项目功能,默认是不启用 xml 文件的热加载功能,想要开启的话通过在项目配置文件中设置 mybatis-xml-reload.enabled 为 true,并指定 mybatis-xml-reload.mapper-locations 属性,也就是 xml 文件位置即可启动。具体配置如下:

# mybatis xml文件热加载配置
mybatis-xml-reload:
  # 是否开启 xml 热更新,true开启,false不开启,默认为false
  enabled: true 
  # xml文件位置,eg: `classpath*:mapper/**/*Mapper.xml,classpath*:other/**/*Mapper.xml`
  mapper-locations: classpath:mapper/*Mapper.xml

关于“mybatis xml文件热加载怎么实现”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“mybatis xml文件热加载怎么实现”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么将Mybatis连接到ClickHouse
  2. 怎么在mybatis中实现一个动态SQL和模糊查询功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis xml

上一篇:js如何判断字符串中是否包含某个字符串

下一篇:linux无法粘贴文件如何解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》