Log optimization when sql exception occurs in mybatis - print sql parameters

 
(Please refer to version 2, because this version has bugs, you must configure the logimp of mybatis, otherwise an error will be reported.
Method: Intercept the parameterize method of StatementHandler through the plug-in. After the StatementHandler object calls the parameterize method to set the parameters, the complete SQL parameters can be obtained.

 

package com.glsys.mybatis3.interceptor;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.jdbc.PreparedStatementLogger;
import org.apache.ibatis.mapping.BoundSql;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Intercepts({
	@Signature(type = StatementHandler.class, method = "parameterize", args = {Statement.class}) })
public class SQLErrorContextInterceptor implements Interceptor {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object obj=invocation.getArgs()[0];
		System.out.println("Before StatementHandler. parameterize()...");
		 System.out.println("Before sql:"+obj.toString());
		  invocation.proceed();
		 System.out.println("Aflter StatementHandler .parameterize()...");
		 System.out.println("Aflter sql:"+obj.toString());
		
		 System.out.println("sql:"+obj.toString());
		 //Method 1: Directly use the toString method of the statment object
		// ErrorContext.instance().sql(obj.toString());
		 //Method 2: Reflection to obtain the PreparedStatementLogger method of the PreparedStatementLogger parent class
		 StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
	     BoundSql boundSql = statementHandler.getBoundSql();
		 Object handler=Proxy.getInvocationHandler(obj);
		 PreparedStatementLogger pstLogger=(PreparedStatementLogger)handler;
		 Class clz=pstLogger.getClass().getSuperclass();
		 Method m=clz.getDeclaredMethod("getParameterValueString");
		 m.setAccessible(true);
		 String logStr=(String) m.invoke(pstLogger);
		 System.out.println(logStr);
		 ErrorContext.instance().sql( boundSql.getSql()+" parameters:"+logStr);
		 return null;
	}

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

	@Override
	public void setProperties(Properties properties) {
		  String dialect = properties.getProperty("dialect");
	        logger.info("mybatis intercept dialect:{}", dialect);
		
	}

}
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326179813&siteId=291194637