SSM統合シリーズのMybatisブロッキングによるSQL文の取得によるSQLモニタリング

7322 ワード

要旨:Mybatisは私たちにInterceptorインタフェースを提供して、このインタフェースを実現することによって私たちの自分のブロッカーを定義することができて、MyBatisブロッカーインタフェースが提供する3つの方法の中で、plugin方法はいくつかのプロセッサ(Handler)の構築過程に使用します.interceptorメソッドは、エージェントクラスの実行を処理するために使用されます.setPropertiesメソッドは、ブロッキングプロパティの設定に使用します.この文書では、ブロックを使用してSQLの実行を取得します.
1.プロジェクト構築は本シリーズの文章、ブログアドレスを参考にすることができる.https://blog.csdn.net/caiqing116/article/details/84573166またはプロジェクト、gitアドレスを直接ダウンロードします.https://github.com/gitcaiqing/SSM_DEMO.git2.MavenがMybatis関連Jarパッケージを導入


	org.mybatis
	mybatis
	3.2.8




	org.mybatis
	mybatis-spring
	1.2.2


3.プロジェクト構成(1)config/jdbc.config構成
#    
jdbc.driverClassName=com.mysql.jdbc.Driver

#   3306    
jdbc.url = jdbc\:mysql\://localhost\:3306/db_ssmdemo?useUnicode\=true&characterEncoding\=UTF-8&allowMultiQueries\=true
jdbc.username = root
jdbc.password = 123456

#   3308    
jdbc.3308.url = jdbc\:mysql\://localhost\:3308/db_ssmdemo?useUnicode\=true&characterEncoding\=UTF-8&allowMultiQueries\=true
jdbc.3308.username = root
jdbc.3308.password = 123456

#        
jdbc.initialSize=2 
#        
jdbc.maxActive=20
#       
jdbc.maxIdle=20
#       
jdbc.minIdle=1
#         
jdbc.maxWait=60000
#           
jdbc.validationQuery=select 1

(2)spring/mybatis.xml構成ブロッキング


	
	
		
		
			 
                classpath:sql/*.xml
            
		
		
		
			
				
			
		
	
	
	
		
		
	
	
  		
	
	


4.MybatisInterceptorがSQLを取得して印刷することを実現する
package com.ssm.datasource;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

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.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.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;

@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 MybatisInterceptor implements Interceptor {
	
	private static final Logger log = LoggerFactory.getLogger(MybatisInterceptor.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];  
        }  

        BoundSql boundSql = mappedStatement.getBoundSql(parameter);  
    	Configuration configuration = mappedStatement.getConfiguration();  
    	Object returnVal = invocation.proceed();
   
    	//  sql  
   	 	String sql = getSql(configuration, boundSql);  
    	log.info("Mybatis      SQL:{}",sql);
    	return returnVal;
	}

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

	@Override
	public void setProperties(Properties arg0) {
	}
	
	/**
	 *   SQL
	 * @param configuration
	 * @param boundSql
	 * @return
	 */
	private String getSql(Configuration configuration, BoundSql boundSql) {
		Object parameterObject = boundSql.getParameterObject();  
	    List parameterMappings = boundSql.getParameterMappings();  
	    String sql = boundSql.getSql().replaceAll("[\\s]+", " ");  
	    if (parameterObject == null || parameterMappings.size() == 0) {
	    	return sql;
	    }  
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();  
        if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {  
        	sql = sql.replaceFirst("\\?", getParameterValue(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 = sql.replaceFirst("\\?", getParameterValue(obj));  
                } else if (boundSql.hasAdditionalParameter(propertyName)) {  
                	Object obj = boundSql.getAdditionalParameter(propertyName);  
                	sql = sql.replaceFirst("\\?", getParameterValue(obj));  
                }  
            }  
        }  
	    return sql;
	}

	private String getParameterValue(Object obj) {  
		String value = null;  
		if (obj instanceof String) {  
			value = "'" + obj.toString() + "'";  
	    } else if (obj instanceof Date) {  
	        DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);  
	        value = "'" + formatter.format(obj) + "'";  
	    } else {  
	        if (obj != null) {  
	            value = obj.toString();  
	        } else {  
	            value = "";  
	        }  
	    }  
	    return value;  
	}  
}

5.プロジェクトの実行印刷ログの監視SQLの表示
[2018-12-25 21:30:42][INFO] Mybatis      SQL:select id, userId, utype, username, password, headimg, realname, sex, age, mobile, email, credate, upddate from tb_basic_user where username = '   '