此次项目中要求把全部mybatis所执行的sql都记录到一个文件中,下面是本身写的一个插件(源是参考网上一个重写mybatis分页插件的例子):java
1.配置插件(在mybatis的配置文件里mybatis.xml配置本身写的这个插件(拦截器)):mysql
<plugins>sql
<!-- mybatis写出sql记录控件(拦截器) -->apache
<plugin interceptor="com.zqgame.interceptors.MyBatisSQLInterceptor"> <!-- 本身写的那个拦截器 -->json
<property name="dialect" value="mysql"/> <!-- mysql的方言 -->mybatis
</plugin>app
</plugins>ide
2.MyBatisSQLInterceptor的内容:ui
package com.zqgame.interceptors;this
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
}
}