package ;
import ;
import ;
import .Date;
import ;
import .Locale;
import ;
import 44j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .Configuration;
import ;
import ;
import .type.TypeHandlerRegistry;
/**
* @author lww
* @date 2020-09-01 00:13
*/
@Slf4j
@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})})
public class PrintSqlInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) ()[0];
Object parameter = null;
if (().length > 1) {
parameter = ()[1];
}
String sqlId = ();
BoundSql boundSql = (parameter);
Configuration configuration = ();
long start = ();
Object returnValue = ();
long time = () - start;
showSql(configuration, boundSql, time, sqlId);
return returnValue;
}
private static void showSql(Configuration configuration, BoundSql boundSql, long time, String sqlId) {
Object parameterObject = ();
List<ParameterMapping> parameterMappings = ();
//替换空格、换行、tab缩进等
String sql = ().replaceAll("[\\s]+", " ");
if (parameterMappings.size() > 0 && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if ((())) {
sql = ("\\?", getParameterValue(parameterObject));
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = ();
if ((propertyName)) {
Object obj = (propertyName);
sql = ("\\?", getParameterValue(obj));
} else if ((propertyName)) {
Object obj = (propertyName);
sql = ("\\?", getParameterValue(obj));
}
}
}
}
logs(time, sql, sqlId);
}
private static String getParameterValue(Object obj) {
String value;
if (obj instanceof String) {
value = "'" + () + "'";
} else if (obj instanceof Date) {
DateFormat formatter = (DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = ();
} else {
value = "";
}
}
return value.replace("$", "\\$");
}
private static void logs(long time, String sql, String sqlId) {
StringBuilder sb = new StringBuilder()
.append(" Time:").append(time)
.append(" ms - ID:").append(sqlId)
.append().append("Execute SQL:")
.append(sql).append();
(());
}
@Override
public Object plugin(Object target) {
return (target, this);
}
@Override
public void setProperties(Properties properties0) {
}
}
复制代码