说明:用过MyBatis框架的同学们都知道,打印SQL日志,可以通过在application.yml配置文件中加入下面配置来设置:
mybatis:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
但打印出来的SQL如下,丑陋不堪,不够优雅
本文介绍如何自定义SQL日志
拦截器
首先,创建一个拦截器,这个拦截器可以拦截住所有访问数据库的操作,在这里面我们可以自己去拼接想要的信息,打印出SQL日志,如下:
import lombok.extern.log4j.Log4j2;
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.springframework.util.ObjectUtils;import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;@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}),@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
@Log4j2
public class MybatisInterceptor implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {// 记录执行SQL前后的时间戳long startTime = System.currentTimeMillis();Object proceed = invocation.proceed();long endTime = System.currentTimeMillis();String printSql = null;try {// 获取执行的SQL, 注意这里没有把拼接SQL放在endTime前面,所以拼接SQL日志是不影响计算的SQL执行时间的。printSql = generateSql(invocation);} catch (Exception exception) {log.error("获取sql异常", exception);} finally {long costTime = endTime - startTime;log.info("【执行的SQL:{}, 耗时:{}ms】", printSql, costTime);}return proceed;}/*** 拼接执行的SQL*/private static String generateSql(Invocation invocation) {MappedStatement statement = (MappedStatement) invocation.getArgs()[0];Object parameter = null;if (invocation.getArgs().length > 1) {parameter = invocation.getArgs()[1];}Configuration configuration = statement.getConfiguration();BoundSql boundSql = statement.getBoundSql(parameter);// 获取参数对象Object parameterObject = boundSql.getParameterObject();List<ParameterMapping> params = boundSql.getParameterMappings();// 获取执行的SQL ==> SELECT id,username,password FROM i_users WHERE id = ?String sql = boundSql.getSql();// 多个空格,用一个空格代替sql = sql.replaceAll("[\\s]+", " ");if (!ObjectUtils.isEmpty(params) && !ObjectUtils.isEmpty(parameterObject)) {// TypeHandlerRegistry 是 MyBatis 用来管理 TypeHandler 的注册器。TypeHandler 用于在 Java 类型和 JDBC 类型之间进行转换TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();// 如果参数对象的类型有对应的 TypeHandler,则使用 TypeHandler 进行处理if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));} else {// 否则,逐个处理参数映射for (ParameterMapping param : params) {String propertyName = param.getProperty();MetaObject metaObject = configuration.newMetaObject(parameterObject);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.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));} else {sql = sql.replaceFirst("\\?", "缺失");}}}}return sql;}/*** 获取参数值*/private static String getParameterValue(Object object) {String value = "";if (object instanceof String) {value = "'" + object + "'";} else if (object instanceof Date) {DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);value = "'" + format.format((Date) object) + "'";} else if (!ObjectUtils.isEmpty(object)) {value = object.toString();}return value;}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}
}
创建完拦截器,再创建一个配置类,将这个拦截器注入到IOC里,如下:
import com.hezy.inteceptor.MybatisInterceptor;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer mybatisConfigurationCustomizer() {return configuration -> {configuration.addInterceptor(new MybatisInterceptor());};}
}
测试
现在,把前面的日志配置去掉。启动项目,访问数据库,查看效果,如下:
非常nice,是不是
总结
本文介绍如何通过MyBatis拦截器,自定义SQL日志,参考微信公众号【小白翻身日志】的文章
- 用了MyBatis的项目 如何优雅地打印SQL
关于MyBatis拦截器的其他使用,可参看下面这篇文章:
- 数据加密的两种方案