拦截器

package com.cares.asis.mybatis.interceptor;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties; import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
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 org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry; /**
* mybatis打印sql 用于在后台打印执行的sql,在applicationContext.xml中的<bean
* id="sqlSessionFactory" 标签中添加:<property name="configLocation"
* value="classpath:mybatis-config.xml" /> 即可打印sql语句 此方法仅用于开发调试,配置之后请勿提交
*/ @Intercepts( { @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }), @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class SqlInterceptor implements Interceptor { private Properties properties; public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = null;
if (invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
}
String sqlId = mappedStatement.getId();
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Configuration configuration = mappedStatement.getConfiguration();
Object returnValue = null;
returnValue = invocation.proceed();
String sql = getSql(configuration, boundSql, sqlId);
System.err.println("ASIS_Print:" + sql);
return returnValue;
} /**
* sql执行的具体位置与sql的拼接
* */
public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId) {
String sql = showSql(configuration, boundSql);
StringBuilder str = new StringBuilder(600);
str.append(sqlId);
str.append(":");
str.append(sql);
return str.toString();
} /**
* 拼接sql中的所有参数
* */
private static String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
} /**
* 解析sql
* */
public static String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (parameterMappings.size() > 0 && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", getParameterValue(parameterObject)); } else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
}
}
}
}
return sql;
} public Object plugin(Object target) {
return Plugin.wrap(target, this);
} public void setProperties(Properties properties0) {
this.properties = properties0;
}
}
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"></property> mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.cares.asis.mybatis.interceptor.SqlInterceptor">
</plugin>
</plugins>
</configuration>

mybatis 打印sql 语句的更多相关文章

  1. 【spring boot】【mybatis】spring boot中mybatis打印sql语句

    spring boot中mybatis打印sql语句,怎么打印出来?[参考:https://www.cnblogs.com/sxdcgaq8080/p/9100178.html] 在applicati ...

  2. logback mybatis 打印sql语句

    logbac.xml 文件的基础配置参考的园友的 http://www.cnblogs.com/yuanermen/archive/2012/02/13/2349609.html 然后hibernat ...

  3. ibatis和myBatis打印sql语句的log4j配置文件

    1/ibatis:  log4j.rootLogger=debug, stdout, logfile   log4j.logger.com.ibatis=DEBUG log4j.logger.com. ...

  4. mybatis 打印SQL语句

    在log4j文件中配置 log4j.rootLogger=DEBUG log4j.logger.com.ibatis=DEBUG log4j.logger.org.mybatis=DEBUG  

  5. spring boot mybatis打印SQL语句

    在logback-spring.xml 文件中添加 <logger name="com.ibatis" level="DEBUG" /> <l ...

  6. mybatis下使用log4j打印sql语句和执行结果

    转载自:https://www.cnblogs.com/jeevan/p/3493972.html 本来以为很简单的问题, 结果自己搞了半天还是不行; 然后google, baidu, 搜出来各种方法 ...

  7. mybatis和redis整合 log4j打印sql语句

    首先,需要在项目中引进jedis-2.8.1.jar包,在pom.xml里加上 <dependency> <groupId>redis.clients</groupId& ...

  8. spring boot打印sql语句-mybatis

    spring boot打印sql语句-mybatis 概述 当自己编写的程序出现了BUG等等,找了很久 调试运行了几遍到mapper层也进去调试进了源码,非常麻烦 我就想打印出sql语句,好进行解决B ...

  9. mybatis日志,打印sql语句,输出sql

    mybatis日志,打印sql语句,输出sql<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE ...

随机推荐

  1. Linux命令(21)查看文件的行数

    在 linux 系统中没有在 windows 系统中那么方便的点点鼠标就可以操作文件了,对文件的各种操作都必须使用各种命令来完成.比如有时候我们需要在不查看文件内容的情况下需要知道该文件有多少行.这个 ...

  2. 利用Gson和SharePreference存储结构化数据

    问题的导入 Android互联网产品通常会有很多的结构化数据需要保存,比如对于登录这个流程,通常会保存诸如username.profile_pic.access_token等等之类的数据,这些数据可以 ...

  3. 理解Python装饰器

    装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓存.权 ...

  4. time.h-------日期与时间函数

    1.clock函数----返回CPU计时单元.函数返回开启这个程序进程到程序中调用clock函数时之间的CPU时钟计时单元(返回毫秒). (计的是占用cpu的时间) 函数原型:long clock() ...

  5. JVM内存结构之二--新生代及新生代里的两个Survivor区(下一轮S0与S1交换角色,如此循环往复)、常见调优参数

    一.为什么会有年轻代 我们先来屡屡,为什么需要把堆分代?不分代不能完成他所做的事情么?其实不分代完全可以,分代的唯一理由就是优化GC性能.你先想想,如果没有分代,那我们所有的对象都在一块,GC的时候我 ...

  6. nodejs初探(四)实现一个多人聊天室

    我们实现的思路是,当有一个人发送过来消息,我们就广播给其他客户端. var net = require('net'); var chatServer = net.createServer(), cli ...

  7. 就是这么简单(续)!使用 RestAssuredMockMvc 测试 Spring MVC Controllers

    就是这么简单(续)!使用 RestAssuredMockMvc 测试 Spring MVC Controllers 转载注明出处:http://www.cnblogs.com/wade-xu/p/43 ...

  8. 【转】JVM内存模型

    http://longdick.iteye.com/blog/473866 图解JVM内存模型 博客分类: JVM JVM活动SUN  /** *  转载请注明作者longdick    http:/ ...

  9. Hardmard 变换

    阿达马(Hadamard)矩阵是由+1和-1元素构成的正交方阵.阿达马变换多被用来计算SATD(一种视频残差信号大小的衡量). 这里介绍三个内容,1. SATD 2. H264中阿达马的应用 3. 阿 ...

  10. Flex加载google地图、百度地图以及天地图作底图

    一  Flex加载Google地图作底图 (1)帮助类GoogleLayer.as /* * 根据输入的地图类型加载Google地图(by chenyuming) */ package Layers ...