拦截器

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. WebApi:过滤器的种类

    WebApi:筛选器的种类 授权筛选器:这些筛选器用于实现IAuthorizationFilter和做出关于是否执行操作方法(如执行身份验证或验证请求的属性)的安全决策.AuthorizeAttrib ...

  2. FW开发代码规范---小任性(2)

    三.空行 (1)在每个函数.结构体.枚举定义结束之后都要加空行. 在一个函数体内,逻辑密切相关的语句之间不加空行,其它地方应加空行分隔. struct st1 { - }; // 空行 enum { ...

  3. CRM合并事件

    1 Only account, contact, lead, incident entities are supported for merge 2 Merging Custom Entity Rec ...

  4. NGUI之UIPanel

    原文:http://www.tasharen.com/forum/index.php?topic=6705.0 概述 UIPanel用来收集和管理它下面所有widget的组件.通过widget的geo ...

  5. (LinkedList)Intersection of Two Linked Lists

    Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...

  6. XE6移动开发环境搭建之IOS篇(2):安装VM9虚拟机(有图有真相)

    网上能找到的关于Delphi XE系列的移动开发环境的相关文章甚少,本文尽量以详细的图文内容.傻瓜式的表达来告诉你想要的答案. 原创作品,请尊重作者劳动成果,转载请注明出处!!! 1.安装VM9英文原 ...

  7. 不让Win7休眠的设置

    1:原因 目前有一个项目是采用微服务的架构搭建的,其中一个微服务的数据库是在一位同事的电脑上(Win7系统),一旦这台电脑休眠,对应的数据库服务就访问不了,所以,需要保持此台电脑永不休眠. 2:傻瓜式 ...

  8. Jquery异步上传图片

    网页中这样: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head id=& ...

  9. 【Tree 2】树形结构数据呈现的非递归算法(循环)实现

    一.基本概况 上一篇博客介绍到用递归实现树结构数据的查找,那么这篇博客,我就结合自己对于树的理解,然后用一种非递归的方式进行树结构数据的处理.首先,改造数据库表设计,加入度的概念: 首先,layer的 ...

  10. 点击弹出固定大小的新窗口(js实现)

    <SCRIPT LANGUAGE="javascript"> <!-- window.open ('page.html') --> </SCRIPT& ...