这次项目中要求把所有mybatis所执行的sql都记录到一个文件中,下面是自己写的一个插件(源是参考网上一个重写mybatis分页插件的例子):

1.配置插件(在mybatis的配置文件里mybatis.xml配置自己写的这个插件(拦截器)):

<plugins>

<!-- mybatis写出sql记录控件(拦截器) -->

   <plugin interceptor="com.zqgame.interceptors.MyBatisSQLInterceptor">  <!-- 自己写的那个拦截器 -->

<property name="dialect" value="mysql"/> <!-- mysql的方言 -->

    </plugin>

</plugins>

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

 

/**

 * 拦截StatementHandler里的 prepare方法把执行的sql进行记录到文件里

 * @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"));/*此处是构造sql文件名称,那个Constant.SQLFILE是自己配的一个常量内容比如为:d:\\,可以随便写*/

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);//将sqlString 写入文件

}

return invocation.proceed();

}

public Object plugin(Object target) {

return Plugin.wrap(target, this);

}

public void setProperties(Properties properties) {

// TODO Auto-generated method stub

}

}