- 首先编写一个Interceptor的实现类,具体代码如下:
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.*;
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;
@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 SqlIntercept implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object proceed = invocation.proceed();
long endTime = System.currentTimeMillis();
String printSql = null;
try {
printSql = generateSql(invocation);
} catch (Exception exception) {
log.error("获取sql异常", exception);
} finally {
long costTime = endTime - startTime;
log.debug("\n\n 执行SQL耗时:{}ms \n {}\n\n\n", costTime, printSql);
}
return proceed;
}
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();
String sql = boundSql.getSql();
sql = sql.replaceAll("[\s]+", " ");
if (!ObjectUtils.isEmpty(params) && !ObjectUtils.isEmpty(parameterObject)) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
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) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
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) {
}
}
- 接着编写一个MyBatis的配置类,将这个插件注册到Spring
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.ycl.interceptor.SqlIntercept;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer mybatisConfigurationCustomizer() {
return configuration -> configuration.addInterceptor(new SqlIntercept());
}
}
- 效果如下
DEBUG c.ycl.aop.TimeAspect - [doAround,26] - 接口总计耗时:65ms
DEBUG c.ycl.aop.TimeAspect - [doAround,26] - 接口总计耗时:0ms
DEBUG c.y.p.m.C.selectList - [debug,137] - ==> Preparing: SELECT id,contract_id,score_condition,description,create_time,update_time,deleted FROM t_calculate_money_rule WHERE deleted=0 AND (contract_id = ?)
DEBUG c.y.p.m.C.selectList - [debug,137] - ==> Parameters: 50(Integer)
DEBUG c.y.p.m.C.selectList - [debug,137] - <== Total: 0
执行SQL耗时:50ms
SELECT id,contract_id,score_condition,description,create_time,update_time,deleted FROM t_calculate_money_rule WHERE deleted=0 AND (contract_id = 50)