Mybatis拦截器实现在SQL执行过程前后对SQL执行时间、SQL信息、Mapper信息进行日志打印

源码

GitHub:https://github.com/291685399/springboot-learning/tree/master/springboot-mybatis02


目标

在SQL执行过程前后进行打印SQL执行时间、SQL信息、Mapper信息进行日志打印如下图所示:
在这里插入图片描述


SqlStatementInterceptor实现Interceptor接口,在SQL执行过程前后进行打印SQL实行时间、SQL信息、Mapper信息进行日志打印输出

import org.apache.ibatis.cache.CacheKey;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * 实现Interceptor接口,在SQL执行过程前后进行打印SQL实行时间、SQL信息、Mapper信息进行日志打印输出
 *
 * @author wyj
 */
@Intercepts(value = {
        @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, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class SqlStatementInterceptor implements Interceptor {

    private static Logger logger = LoggerFactory.getLogger(SqlStatementInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        try {
            return invocation.proceed();//执行sql过程
        } finally {
            long endTime = System.currentTimeMillis();
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];//获取xml中的一个select/update/insert/delete节点,主要描述的是一条SQL语句
            Object parameter = "";
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
                logger.info("==> transmit Parameters is [ {} ]", parameter);//打印入参参数
            }
            String sqlId = mappedStatement.getId(); // 获取到节点的id,即sql语句的id
            String[] mappers = getMapper(sqlId);
            logger.info("==> execute Mapper name is [ {} ]", mappers[0]);//打印执行的Mapper名称
            logger.info("==> execute Mapper method is [ {} ]", mappers[1]);//打印执行的Mapper方法
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);// BoundSql就是封装myBatis最终产生的sql类
            Configuration configuration = mappedStatement.getConfiguration();// 获取节点的配置
            logger.info("==> execute SQL with Parameters is [ {} ]", getSql(configuration, boundSql));//打印执行带参SQL
            logger.info("==> execute SQL cost [ {} ] ms", (endTime - startTime));//打印SQL执行时间
        }
    }

    /**
     * 根据节点id获取执行的Mapper name和Mapper method
     *
     * @param sqlId 节点id
     * @return
     */
    public static String[] getMapper(String sqlId) {
        int index = sqlId.lastIndexOf(".");
        String mapper = sqlId.substring(0, index);
        String method = sqlId.substring(index + 1);
        return new String[]{mapper, method};
    }

    /**
     * 获取带参SQL
     *
     * @param configuration 节点的配置
     * @param boundSql      封装myBatis最终产生的sql类
     * @return
     */
    public static String getSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();//获取参数
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");//sql语句中多个空格都用一个空格代替
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); //获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换。如果根据parameterObject.getClass()可以找到对应的类型,则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);//MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);//该分支是动态sql
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        sql = sql.replaceFirst("\\?", "缺失");//打印出缺失,提醒该参数缺失并防止错位
                    }
                }
            }
        }
        return sql;
    }

    /**
     * 对SQL进行格式化
     *
     * @param obj
     * @return
     */
    private static 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(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

MyBatisConfig用于将实现的mybatis拦截器、mapper xml配置文件的路径和别名包的路径设置到SqlSessionFactory中

import com.wyj.interceptor.SqlStatementInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 用于将实现的mybatis拦截器、mapper xml配置文件的路径和别名包的路径设置到SqlSessionFactory中
 *
 * @author wyj
 */
@Configuration
public class MyBatisConfig {

    @Autowired
    private DataSource dataSource;

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{new SqlStatementInterceptor()});
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(mapperLocations));
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return sqlSessionFactoryBean.getObject();
    }
}

application.properties这里需要配置mapper的包路径日志级别为DEBUG

### tomcat ###
server.port=8080
### datasource ###
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot-mybatis02?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
### mybatis ###
mybatis.mapper-locations=classpath*:mapper/*.xml
mybatis.type-aliases-package=com.wyj.entity
#logging
logging.level.com.wyj.mapper=debug

执行效果
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
语句并进行修改? Mybatis拦截器可以通过Invocation对象获取完整的SQL语句并进行修改。在拦截器的intercept方法中,可以获取到方法调用的相关信息,包括Mapper接口、方法名、方法参数等。通过这些信息,可以获取到BoundSql对象,它包含了原始的SQL语句和参数信息。可以通过BoundSql对象获取完整的SQL语句并进行修改,然后再将修改后的SQL语句设置回BoundSql对象即可。 具体实现可以参考以下代码: ``` public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) args[0]; Object parameterObject = args[1]; BoundSql boundSql = mappedStatement.getBoundSql(parameterObject); String sql = boundSql.getSql(); // 在这里对SQL语句进行修改 String newSql = modifySql(sql); // 将修改后的SQL语句重新设置回BoundSql对象中 BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), newSql, boundSql.getParameterMappings(), parameterObject); MappedStatement newMappedStatement = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql)); args[0] = newMappedStatement; return invocation.proceed(); } private String modifySql(String sql) { // 在这里可以对SQL语句进行修改,例如添加分页的limit条件 return "select * from (" + sql + ") limit 0, 10"; } private MappedStatement copyFromMappedStatement(MappedStatement mappedStatement, SqlSource newSqlSource) { MappedStatement.Builder builder = new MappedStatement.Builder(mappedStatement.getConfiguration(), mappedStatement.getId(), newSqlSource, mappedStatement.getSqlCommandType()); builder.resource(mappedStatement.getResource()); builder.fetchSize(mappedStatement.getFetchSize()); builder.statementType(mappedStatement.getStatementType()); builder.keyGenerator(mappedStatement.getKeyGenerator()); builder.keyProperty(mappedStatement.getKeyProperty()); builder.timeout(mappedStatement.getTimeout()); builder.parameterMap(mappedStatement.getParameterMap()); builder.resultMaps(mappedStatement.getResultMaps()); builder.cache(mappedStatement.getCache()); builder.useCache(mappedStatement.isUseCache()); return builder.build(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值