在使用mybatis或者mybatis-plus作为orm框架的时候,会发现默认的日志输出是下面这样的

在参数少并且sql简单的情况下,这样的sql我们能通过手动去替换占位符,来获取到真正执行的sql。但是如果是比较复杂的sql,或者查询参数比较多的话,一个个替换就比较费时费力了。
mybatis plugin于是我们就可以使用mybatis对外暴露出的interceptor接口,来手动实现一个能优雅地打印日志的插件。平常像用的比较多的pagehelper,就是一个mybatis的插件,实现原理和我们这次要做的功能十分相似。
mybatis插件的原理
mybatis插件的实现原理基于java的动态代理机制。当mybatis框架在初始化时检测到有插件配置,它会为目标对象(如executor、statementhandler等)创建一个代理对象。这个代理对象会包装原始对象,并在方法调用时执行自定义的拦截逻辑。
拦截过程中,如果存在拦截器,且方法的签名与拦截器配置的方法签名匹配,则调用拦截器的intercept方法。在intercept方法中,开发者可以实现自定义的拦截逻辑,通常这里会包含对原始方法调用的修改或增强
mybatis 插件的几个重点模块
- @intercepts 注解:这是 mybatis 提供的一个注解,用于定义一个拦截器。一个拦截器可以拦截一个或多个方法。
- @signature 注解:这是 @intercepts 注解的子注解,用于指定要拦截的目标方法。
@signature 注解的参数分别是:
- type:指定要拦截的接口类型。
- method:指定要拦截的方法名。
- args:指定要拦截的方法的参数类型列表。
实现一个优雅打日志的功能
首先编写一个interceptor的实现类,具体代码如下,所有的注释都放在代码上了:
其中类上的intercepts注解含义为:在 executor 的 query、update 方法执行前后进行自定义的处理,其中executor 是最底层的执行器,负责与数据库进行通信。它的职责包括创建和缓存 statement 对象、执行 sql 语句、处理结果集等。
package com.xa.demo1.config;
import lombok.extern.slf4j.slf4j;
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.interceptor;
import org.apache.ibatis.plugin.intercepts;
import org.apache.ibatis.plugin.invocation;
import org.apache.ibatis.plugin.plugin;
import org.apache.ibatis.plugin.signature;
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.properties;
import java.util.regex.matcher;
/**
* @author akazaakari 实现一个优雅打日志的功能
* @intercepts 注解:
*
* 这是 mybatis 提供的一个注解,用于定义一个拦截器。一个拦截器可以拦截一个或多个方法。
* @signature 注解:
*
* 这是 @intercepts 注解的子注解,用于指定要拦截的目标方法。
*
* @signature 注解的参数分别是:
*
* type:指定要拦截的接口类型。
*
* method:指定要拦截的方法名。
*
* args:指定要拦截的方法的参数类型列表。
* todo: 这一章其他内容之后补上(intercepts注解、mybatis插件开发过程中的各个对象
*/
@intercepts({
@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}),
@signature(type = executor.class, method = "update", args = {mappedstatement.class, object.class})
})
@slf4j
public class sqlinterceptor implements interceptor {
@override
public object intercept(invocation invocation) throws throwable {
// 计算这一次sql执行钱后的时间,统计一下执行耗时
long starttime = system.currenttimemillis();
object proceed = invocation.proceed();
long endtime = system.currenttimemillis();
string printsql = null;
try {
// 通过generatesql方法拿到最终生成的sql
printsql = generatesql(invocation);
}catch (exception exception){
log.error("获取sql异常",exception);
}finally {
// 拼接日志打印过程
long costtime = endtime - starttime;
log.info("\n 执行sql耗时:{}ms \n 执行sql:{}",costtime,printsql);
}
return proceed;
}
private static string generatesql(invocation invocation){
// 获取到boundsql以及configuration对象
// boundsql 对象存储了一条具体的 sql 语句及其相关参数信息。
// configuration 对象保存了 mybatis 框架运行时所有的配置信息
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
string sql = boundsql.getsql();
// sql中多个空格使用一个空格代替
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);
// 检查对象中是否存在该属性的 getter 方法,如果存在就取出来进行替换
if (metaobject.hasgetter(propertyname)){
object obj = metaobject.getvalue(propertyname);
sql = sql.replacefirst("\\?", matcher.quotereplacement(getparametervalue(obj)));
// 检查 boundsql 对象中是否存在附加参数。附加参数可能是在动态 sql 处理中生成的,有的话就进行替换
}else if (boundsql.hasadditionalparameter(propertyname)){
object obj = boundsql.getadditionalparameter(propertyname);
sql = sql.replacefirst("\\?", matcher.quotereplacement(getparametervalue(obj)));
}else {
// 如果都没有,说明sql匹配不上,带上“缺失”方便找问题
sql = sql.replacefirst("\\?", "缺失");
}
}
}
}
return sql;
}
private static string getparametervalue(object object) {
string value = "";
if (object instanceof string){
value = "'" + object.tostring() + "'";
}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;
}
@override
public object plugin(object target) {
return plugin.wrap(target, this);
}
@override
public void setproperties(properties properties) {
// 可以通过properties配置插件参数
}
}
接着编写一个mybatis的配置类,将这个插件注册进去
/**
* @title: mybatisconfigurationcustomizer
* @description: 编写一个mybatis的配置类,将这个插件注册进去
* @createddate: 2024/06/16 00:06
* @param
* @return configurationcustomizer
**/
@bean
public configurationcustomizer mybatisconfigurationcustomizer() {
return configuration -> {
configuration.addinterceptor(new sqlinterceptor());
};
}
实现功能如图所示

到此这篇关于mybatis/mybatis_plus项目打印sql的方法实现的文章就介绍到这了,更多相关mybatis_plus打印sql内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论