Write an interception plug-in for mybatis to write all executed sql into the file

The original http://3131854.blog.51cto.com/3121854/1147446
mybatis uses interceptors to display sql and uses druid to configure connection information http://www.cnblogs.com/babyhhcsy/p/4500884.html



@Intercepts( { 
       @ Signature(method = "query", type = Executor.class, args = { 
              MappedStatement.class, Object.class, RowBounds.class, 
              ResultHandler.class }), 
       @Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class }) }) 
@Intercepts marks this as an Interceptor, and then defines two @Signatures in @Intercepts, that is, two interception points. For the first @Signature, we define that the Interceptor will intercept the query methods of the Executor interface whose parameters are of type MappedStatement, Object, RowBounds and ResultHandler; for the second @Signature, we define that the Interceptor will intercept the prepare method of the StatementHandler whose parameter type is Connection. .


In this project, it is required to record all the sql executed by mybatis in a file. The following is a plug-in written by myself (the source is an example of rewriting the mybatis paging plug-in on the Internet):

1. Configure the plug-in (in the configuration of mybatis) Mybatis.xml in the file configures this plugin (interceptor) written by myself):
<plugins>
	<!-- mybatis writes the sql record control (interceptor) -->
   <plugin interceptor="com.zqgame.interceptors.MyBatisSQLInterceptor"> <!-- The interceptor I wrote myself-->
	<property name="dialect" value="mysql"/> <!-- mysql的方言 -->
    </plugin>
</plugins>


2. Contents of MyBatisSQLInterceptor:
package com.zqgame.interceptors;
 
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
/*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.apache.ibatis.reflection.MetaObject;
import com.zqgame.common.Constant;
 
/**
 * Intercept the prepare method in StatementHandler to record the executed sql to the file
 * @author panguixiang
 *
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class MyBatisSQLInterceptor implements Interceptor {
	public Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		MetaObject metaStatementHandler = MetaObject.forObject(statementHandler);
		String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");//获得sql
		/* * if(log.isDebugEnabled()){ log.debug("生成分页SQL : "+boundSql.getSql());* }*/
		File sqlFile = null;
		List<String> lines = null;
		@SuppressWarnings("unchecked")
		HashMap<String, String> mapParam = (HashMap<String, String>) metaStatementHandler.getValue("delegate.boundSql.parameterObject");
		synchronized (this) {
			sqlFile = new File(Constant.SQLFILE.concat(
					DateFormatUtils.format(new Date(), "yyyyMMdd")).concat("-sql.txt"));/*This is the name of the constructed sql file, and the Constant.SQLFILE is a constant content that is assigned by itself, such as: d:\\, you can write whatever you want */
			lines = new ArrayList<String>();
			lines.add(originalSql.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" +", " "));
			JSONObject jsonObject = JSONObject.fromObject (mapParam);
			lines.add(jsonObject.toString());
			FileUtils.writeLines(sqlFile, "utf-8", lines, true);//Write sqlString to file
		}
		return invocation.proceed();
	}
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326994438&siteId=291194637