本插件可以直接在控制台中输出MyBatis的真实SQL语句(替换参数后的SQL语句)及SQL耗时,方便开发调试过程。
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.mapping.SqlCommandType;
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 org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
@Component
@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})}
)
public class SqlInterceptor implements Interceptor {
private static final Logger log = LoggerFactory.getLogger(SqlInterceptor.class);
@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];
}
String sqlId = mappedStatement.getId();
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Configuration configuration = mappedStatement.getConfiguration();
long startTime = System.currentTimeMillis();
Object result = null;
try {
result = invocation.proceed();
} finally {
try {
long sqlCostTime = System.currentTimeMillis() - startTime;
String sql = getSql(configuration, boundSql);
String returnSql = formatSqlLog(mappedStatement.getSqlCommandType(), sqlId, sql, sqlCostTime, result);
log.warn(returnSql);
// log.warn("");
} catch (Exception ignored) {
System.out.println("Mybatis插件报错");
ignored.printStackTrace();
}
}
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
if (properties == null) {
return;
}
}
private String getSql(Configuration configuration, BoundSql boundSql) {
// 输入sql字符串空判断
String sql = boundSql.getSql();
if (sql == null || sql.length() == 0) {
return "";
}
//美化sql
sql = beautifySql(sql);
//填充占位符, 目前基本不用mybatis存储过程调用,故此处不做考虑
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (!parameterMappings.isEmpty() && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = this.replacePlaceholder(sql, 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 = replacePlaceholder(sql, obj);
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = replacePlaceholder(sql, obj);
}
}
}
}
return sql;
}
private String beautifySql(String sql) {
return sql.replaceAll("[\\s\n ]+", " ");
}
private String replacePlaceholder(String sql, Object parameterObject) {
String result;
if (parameterObject instanceof String) {
result = "'" + parameterObject.toString() + "'";
} else if (parameterObject instanceof Date) {
result = "'to_date('" + getDate2String((Date) parameterObject) + "','yyyy-mm-dd hh24:mi:ss')";
} else {
result = parameterObject.toString();
}
return sql.replaceFirst("\\?", result);
}
private String getDate2String(Date parameterObject) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(parameterObject);
}
private String formatSqlLog(SqlCommandType sqlCommandType, String sqlId, String sql, long costTime, Object obj) {
String returnSql = String.format("[%s] SQL执行耗时:[%dms] \nSQL输出 :%s", sqlId, costTime, sql);
if (sqlCommandType == SqlCommandType.UPDATE || sqlCommandType == SqlCommandType.INSERT || sqlCommandType == SqlCommandType.DELETE) {
if (null != obj) {
returnSql += "\n受影响行数为: ===> " + obj;
}
}
return returnSql;
}
}