美文网首页
ThreadLocal获取mybatis执行sql

ThreadLocal获取mybatis执行sql

作者: 鸿晕晕晕晕晕yyy | 来源:发表于2021-01-13 10:38 被阅读0次

    1.ThreadLocal原理:

    ThreadLocal的作用就是:线程安全。
    ThreadLocal的本质就是一个内部的静态的map,key是当前线程的句柄,value是需要保持的值。
    由于是内部静态map,不提供遍历和查询的接口,每个线程只能获取自己线程的value。
    这样,就线程安全了,又提供了数据共享的能力
    具体可以参考:
    [ThreadLocal] https://my.oschina.net/u/4006148/blog/2876618

    2.创建单例ThreadLocal作为工具类使用

    注意:

    • 静态类一般当作工具类使用;单例用作存储上下文数据
    package com.example.fileUtils;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    /**
     * 单例模式
     * @author shihy
     * @date 2021/1/12 18:08
     * @description
     */
    public enum ThreadLocalSingleton {
        INSTANCE;
        private ThreadLocal<List<String>> data = new ThreadLocal<List<String>>() {
            @Override
            protected List<String> initialValue() {
                return new ArrayList<String>();
            }
        };
    
        public List<String> getData() {
            return data.get();
        }
    
        public void setData(String sql) {
            List<String> cacheList = data.get();
            cacheList.add(sql);
            data.set(cacheList);
        }
    
        public void removeData(){
            data.remove();
        }
        public static ThreadLocalSingleton getInstance() {
            return INSTANCE;
        }
    }
    

    3.写一个拦截器拦截执行sql

    具体使用方法可以参考:https://blog.csdn.net/wuyuxing24/article/details/89343951

    package com.example.fileUtils;
    
    /**
     * @author shihy
     * @date 2021/1/11 12:00
     * @description
     */
    
    import org.apache.ibatis.executor.Executor;
    import org.apache.ibatis.mapping.BoundSql;
    import org.apache.ibatis.mapping.MappedStatement;
    import org.apache.ibatis.mapping.ParameterMapping;
    import org.apache.ibatis.plugin.*;
    import org.apache.ibatis.reflection.MetaObject;
    import org.apache.ibatis.session.Configuration;
    import org.apache.ibatis.session.ResultHandler;
    import org.apache.ibatis.session.RowBounds;
    import org.apache.ibatis.type.TypeHandlerRegistry;
    import org.springframework.stereotype.Component;
    
    import java.text.DateFormat;
    import java.util.*;
    
    /**
     * 自定义mybatis插件,实现输出实际执行sql语句
     *
     * @author tangjizhouchn@foxmail.com
     * @date 2019-08-18
     */
    @Intercepts({
            @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
            @Signature(type = Executor.class, method = "query",  args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class })
    })
    @Component
    public class newInceterceptor implements Interceptor {
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }
    
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            Configuration configuration = mappedStatement.getConfiguration();
            //获取sql语句,拼装参数
            String sql = getSql(configuration, boundSql);
            //放入ThreadLocal上下文
            ThreadLocalSingleton instance = ThreadLocalSingleton.getInstance();
            instance.setData(sql);
            Object returnVal = invocation.proceed();
            return returnVal;
        }
    
        @Override
        public Object plugin(Object target) {
            return Plugin.wrap(target, this);
        }
    
        @Override
        public void setProperties(Properties arg0) {
        }
        /**
         * 获取SQL
         * @param configuration
         * @param boundSql
         * @return
         */
        private String getSql(Configuration configuration, BoundSql boundSql) {
            Object parameterObject = boundSql.getParameterObject();
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
            if (parameterObject == null || parameterMappings.size() == 0) {
                return sql;
            }
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
            return sql;
        }
        private String getParameterValue(Object obj) {
            String value = null;
            if (obj instanceof String) {
                value = "'" + obj.toString() + "'";
            } else if (obj instanceof Date) {
                DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
                value = "'" + formatter.format(obj) + "'";
            } else {
                if (obj != null) {
                    value = obj.toString();
                } else {
                    value = "";
                }
            }
            return value;
        }
    }
    

    4.写一个切面拦截controller层返回结果

    package com.example.fileUtils;
    
    import com.example.entity.StudentEntity;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    /**
     * @author shihy
     * @date 2021/1/12 15:54
     * @description
     */
    
    @Component
    @Aspect
    public class WebControllerAop {
    
        @Pointcut("execution(* com.example.controller..*.*(..))")
        public void executeService() {
    
        }
        /**
         * 后置返回通知
         * 这里需要注意的是:
         * 如果参数中的第一个参数为JoinPoint,则第二个参数为返回值的信息
         * 如果参数中的第一个参数不为JoinPoint,则第一个参数为returning中对应的参数
         * returning 限定了只有目标方法返回值与通知方法相应参数类型时才能执行后置返回通知,否则不执行,对于returning对应的通知方法参数为Object类型将匹配任何目标返回值
         */
        @AfterReturning(value = "execution(* com.example.controller..*.*(..))", returning = "keys")
        public void doAfterReturningAdvice1(JoinPoint joinPoint, Object keys) {
            ThreadLocalSingleton instance = ThreadLocalSingleton.getInstance();
            Message message = (Message) keys;
            //获取执行sql值
            List<String> sqlList = instance.getData();
            String sql = "";
            if(sqlList!= null && sqlList.size()>0) {
                sql = String.join(";\n", sqlList);
            }
            //对controller返回的message插入执行sql
            message.setSqlInfo(sql);
            instance.removeData();
        }
    }
    

    gitee地址:https://gitee.com/gsshy/spring_boot_example

    相关文章

      网友评论

          本文标题:ThreadLocal获取mybatis执行sql

          本文链接:https://www.haomeiwen.com/subject/lhquaktx.html