mybatis 拦截器处理日志

参考文章:
https://www.mybatis.org/mybatis-3/zh/configuration.html#plugins
https://www.cnblogs.com/fangjian0423/p/mybatis-interceptor.html
https://www.cnblogs.com/Xrq730/P/6972268.Html

目前只支持map参数、字符串参数类型、oracle语法。

配置文件中加入

<plugins>
  <plugin interceptor="connTest.conn.LogInterceptor">
  plugin>
plugins>
package connTest.conn;

import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.FastResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
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.session.ResultHandler;

@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 })})
public class LogInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        
        long startTime = System.currentTimeMillis();
        
        StatementHandler statementHandler = (StatementHandler)target;
        
        try {
            return invocation.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            long sqlCost = endTime - startTime;
            
            BoundSql boundSql = statementHandler.getBoundSql();
            String sql = boundSql.getSql();
            Object parameterObject = boundSql.getParameterObject();
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
            
            // 格式化Sql语句,去除换行符,替换参数
            sql = formatSql(sql, parameterObject, parameterMappingList);
            
            System.out.println("执行耗时[" + sqlCost + "ms] " + "SQL:" + sql + ";");
            
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        
    }
    
    @SuppressWarnings("unchecked")
    private String formatSql(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) {
        
//        if(sql == null || sql.length() == 0 || parameterObject == null 
//        		|| parameterMappingList == null || parameterMappingList.size() == 0){
//        	return sql;
//        }
    	
    	if(parameterObject == null){
    		sql = sql.replaceAll(" \\?", " null");
    		sql = sql.replaceAll("\r|\n|\t", " ").replaceAll("\\s+", " ");
    		return sql;
    	}
        
        //System.out.println(" class : " + parameterObject.getClass());
    	//bean需要反射,有时间再写
        if(Map.class.isAssignableFrom(parameterObject.getClass())){
        	Map pb = (Map)parameterObject;
        	for(ParameterMapping temp: parameterMappingList){
        		
        		//System.out.println(temp.getJavaType());
        		sql = sql.replaceFirst(" \\?", pb.get(temp.getProperty()) == null ? " null" : " '" +(String)pb.get(temp.getProperty()) + "'");
        		sql = sql.replaceAll("\r|\n|\t", " ").replaceAll("\\s+", " ");
        	}
        }
        
        return sql;
    }
    
}

效果

执行耗时[37ms] SQL:select 'a1' "p1", null p2, 'a3' from dual where 1 = 1 and 'a1' = '1';

你可能感兴趣的:(mybatis,java)