java拦截执行的sql,写个mybatis的拦截插件,实现将所有执行的sql写入文件里

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

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

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 lines = null;

@SuppressWarnings("unchecked")

HashMap mapParam = (HashMap) 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();

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值