使用反射和动态代理实现mybaits的mapping.xml热部署

MyBatis XML映射热重载
本文介绍了一种实现MyBatis中XML映射文件热重载的方法,通过反射和代理技术来动态刷新已加载的XML配置,使得开发过程中无需重启应用即可更新数据映射逻辑。
package com.apexsoft.citic.managed.assistance.module.backdoor.service;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


@Service
public class BackdoorService {

    private static Logger log = Logger.getLogger(BackdoorService.class);

    @Resource
    SqlSession sqlSession;

    private static long lastRefreshMapperTime = System.currentTimeMillis();
    private static boolean isModifiedStrictMapOfConfiguration = false;

    public Set<String> refreshMappper() throws NoSuchFieldException, IllegalAccessException, IOException {
        long startRefreshMapperTime = System.currentTimeMillis();
        Configuration configuration = sqlSession.getConfiguration();
        Field loadedResourcesField = configuration.getClass().getDeclaredField("loadedResources");
        loadedResourcesField.setAccessible(true);
        Set<String> loadedResources = (Set<String>) loadedResourcesField.get(configuration);
        Set<String> loadedResourcesBak = new HashSet<String>(loadedResources);
        Set<String> refreshedResources = new HashSet<String>();
        for (String resource : loadedResourcesBak) {
            if (resource.endsWith(".xml") && isNeedRefresh(resource)) {
                loadedResources.remove(resource);
                if(!isModifiedStrictMapOfConfiguration){
                    modifyStrictMapOfConfiguration(configuration);
                }
                //使用classloader.getResource().openStream() 可以清除缓存
                InputStream inputStream = Thread.currentThread().getContextClassLoader().getResource(resource).openStream();
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                mapperParser.parse();
                refreshedResources.add(resource);
            }
        }
        lastRefreshMapperTime = startRefreshMapperTime;
        return refreshedResources;
    }

    private synchronized void modifyStrictMapOfConfiguration(Configuration configuration) throws NoSuchFieldException, IllegalAccessException {
        if (!isModifiedStrictMapOfConfiguration){
            isModifiedStrictMapOfConfiguration = true;
            // 清理原有资源,更新为自己的StrictMap方便,增量重新加载
            String[] mapFieldNames = new String[]{"mappedStatements", "caches", "resultMaps", "parameterMaps", "keyGenerators", "sqlFragments"};
            for (String fieldName : mapFieldNames) {
                Field field = configuration.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Map map = ((Map) field.get(configuration));
                InvocationHandler invocationHandler = new StrictMapInvocationHandler(map);
                Map mapProxy = (Map)Proxy.newProxyInstance(map.getClass().getClassLoader(), map.getClass().getSuperclass().getInterfaces(), invocationHandler);
                field.set(configuration, mapProxy);
            }
        }
    }
    
    private boolean isNeedRefresh(String resource) {
        String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
        File file = new File(nodepath + resource);
        if (file.lastModified() < lastRefreshMapperTime) {
            return false;
        }
        return true;
    }

    protected class StrictMapInvocationHandler implements InvocationHandler{

        private Map target;

        public StrictMapInvocationHandler(Map target){
            super();
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(method.getName().equals("put")){
                String key = args[0].toString();
                target.remove(key);
                log.info("refresh key:" + key.substring(key.lastIndexOf(".") + 1));
            }
            return method.invoke(target, args);
        }
    }
}

ps: 目前代码只是实现了mapping.xml的重新加载,可以作为java热部署技术的补充

MyBatis 中,`mapper.xml` 文件是用于定义 SQL 语句 Java 方法之间映射关系的核心配置文件。查询 SQL 语句是其中最常用的元素之一,它负责从数据库中检索数据,并将结果映射到 Java 对象中。查询语句的编写需要关注 SQL 本身、参数的传递方式以及结果集的映射规则。 ### 查询语句的基本结构 MyBatis 的查询语句通过 `<select>` 标签定义,其中包含多个属性来控制 SQL 的执行结果映射。一个基本的查询语句如下所示: ```xml <select id="findById" parameterType="int" resultType="blog"> SELECT * FROM blog WHERE id = #{id} </select> ``` - `id`:该属性值必须与对应的 Mapper 接口中的方法名一致,用于将 SQL 语句与接口方法绑定。 - `parameterType`:指定传入参数的类型,可以是基本类型(如 `int`)、Java Bean 或 Map。 - `resultType`:指定查询结果映射的目标类型,可以是基本类型、Java Bean 或 Map。如果查询返回的是多条记录,MyBatis 会自动将其转换为集合类型。 ### 参数传递方式 MyBatis 支持多种参数传递方式,包括单个参数、多个参数、Java Bean Map。 #### 单个参数 当方法只有一个参数时,可以直接使用 `#{参数名}` 来引用该参数。例如: ```xml <select id="findById" parameterType="int" resultType="blog"> SELECT * FROM blog WHERE id = #{id} </select> ``` #### 多个参数 当方法有多个参数时,可以通过 `@Param` 注解为每个参数指定名称,然后在 SQL 中引用这些名称: ```java Blog findByTitleAndAuthor(@Param("title") String title, @Param("author") String author); ``` 对应的 XML 配置如下: ```xml <select id="findByTitleAndAuthor" resultType="blog"> SELECT * FROM blog WHERE title = #{title} AND author = #{author} </select> ``` #### Java Bean 参数 当参数是一个 Java Bean 时,可以直接在 SQL 中使用 `#{属性名}` 来引用对象的属性: ```java int insertBlog(Blog blog); ``` 对应的 XML 配置如下: ```xml <insert id="insertBlog"> INSERT INTO blog (title, author, content) VALUES (#{title}, #{author}, #{content}) </insert> ``` #### Map 参数 当参数是 Map 类型时,可以直接使用 `#{key}` 来引用 Map 中的值: ```java Blog findByMap(Map<String, Object> params); ``` 对应的 XML 配置如下: ```xml <select id="findByMap" resultType="blog"> SELECT * FROM blog WHERE title = #{title} AND author = #{author} </select> ``` ### 结果集映射 MyBatis 提供了灵活的结果集映射机制,支持自动映射手动映射。 #### 自动映射 当数据库列名与 Java Bean 属性名一致时,MyBatis 会自动进行映射。例如: ```xml <select id="findAll" resultType="blog"> SELECT * FROM blog </select> ``` 如果 `blog` 表的列名与 `Blog` 类的属性名完全匹配,MyBatis 会自动将每行数据转换为 `Blog` 对象。 #### 手动映射 当数据库列名与 Java Bean 属性名不一致时,可以通过 `<resultMap>` 显式定义映射关系: ```xml <resultMap id="blogResultMap" type="blog"> <id property="id" column="blog_id"/> <result property="title" column="blog_title"/> <result property="author" column="blog_author"/> <result property="content" column="blog_content"/> </resultMap> <select id="findAll" resultMap="blogResultMap"> SELECT * FROM blog </select> ``` 上述配置中,`<resultMap>` 定义了数据库列与 Java Bean 属性之间的映射关系,`<select>` 标签通过 `resultMap` 属性引用该映射关系。 ### 动态 SQL 查询 MyBatis 还支持动态 SQL 查询,可以根据条件拼接 SQL 语句。常用的动态 SQL 标签包括 `<if>`、`<choose>`、`<when>`、`<otherwise>` `<where>`。 #### `<if>` 标签 `<if>` 标签用于根据条件动态生成 SQL 片段: ```xml <select id="findBlogs" resultType="blog"> SELECT * FROM blog <where> <if test="title != null"> AND title LIKE CONCAT('%', #{title}, '%') </if> <if test="author != null"> AND author LIKE CONCAT('%', #{author}, '%') </if> </where> </select> ``` #### `<choose>`、`<when>` `<otherwise>` 标签 这些标签用于实现类似 `switch-case` 的逻辑: ```xml <select id="findBlogs" resultType="blog"> SELECT * FROM blog <where> <choose> <when test="title != null"> AND title LIKE CONCAT('%', #{title}, '%') </when> <when test="author != null"> AND author LIKE CONCAT('%', #{author}, '%') </when> <otherwise> AND 1=1 </otherwise> </choose> </where> </select> ``` ### 总结 MyBatis 的 `mapper.xml` 文件中的查询 SQL 语句具有高度的灵活性可扩展性。通过合理使用 `<select>` 标签及其相关属性,结合参数传递方式结果集映射机制,可以轻松实现复杂的数据库查询操作。此外,MyBatis 提供的动态 SQL 功能使得根据不同的业务需求构建灵活的查询语句成为可能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值