寫個mybatis的攔截插件,實現將全部執行的sql寫入文件裏

 此次項目中要求把全部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

}

}

相關文章
相關標籤/搜索