java sql 美化插件_Mybatis插件-sql日志美化输出

同步自本人博客

mybatis有基本的sql日志,但是看起来很不舒服,sql一行参数在另一行,查询多的时候sql行和参数行分开很远。下面就是相同颜色的是一组:

看了大哥的文章决定试试弄个美化日志的mybatis插件,其中还增加了对通用mapper Example查询、日期参数和自定义String[] TypeHandle参数的处理,废话不多说上代码:

@Component

@Profile({"dev", "test"})

@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),

@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),

@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})

@Slf4j

public class SqlCastInInterceptor implements Interceptor {

@Override

public Object intercept(Invocation invocation) throws Throwable {

Object target = invocation.getTarget();

long startTime = System.currentTimeMillis();

StatementHandler statementHandler = (StatementHandler) target;

int size = 0;

try {

Object o = invocation.proceed();

if (isList(o.getClass())) {

size = ((List) o).size();

}

return o;

} finally {

long endTime = System.currentTimeMillis();

long sqlCost = endTime - startTime;

BoundSql boundSql = statementHandler.getBoundSql();

String sql = boundSql.getSql();

Object parameterObject = boundSql.getParameterObject();

List parameterMappingList = boundSql.getParameterMappings();

// 格式化Sql语句,去除换行符,替换参数

sql = formatSql(sql, parameterObject, parameterMappingList);

log.debug("SQL:[" + sql + "]执行耗时[" + sqlCost + "ms]结果集[" + size + "]");

}

}

@Override

public Object plugin(Object target) {

return Plugin.wrap(target, this);

}

@Override

public void setProperties(Properties properties) {

log.info("set properties");

}

/**

* @param sql 没花钱sql

* @param parameterObject 参数

* @param parameterMappingList 参数map

* @return 美化后sql

* 增加代码可以处理通用mapper的Example参数美化sql

*/

@SuppressWarnings("unchecked")

private String formatSql(String sql, Object parameterObject, List parameterMappingList) {

// 输入sql字符串空判断

if (sql == null || sql.length() == 0) {

return "";

}

你可能感兴趣的:(java,sql,美化插件)