1、在mybatis-config.xml配置中添加setting配置参数,会打印SQL执行结果
<?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>
<settings>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration> 2、在spring-mybatis配置文件中添加配置参数
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:xxx/xxx/xxx/xxx/*.xml"></property>
</bean> 备注: 之前通过log4j的配置文件方式来实现,没有成功!!!项目环境:ssm+shiro 第二种方式(通过拦截器的方式)
1、在sqlSessionFactory 配置参数中,添加参数配置:
<property name="plugins">
  <list>
    <bean class="xxx.MybatisInterceptor"></bean>
  </list>
</property>

2、mybatis sql拦截器类
package xxx;

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;
import org.apache.log4j.Logger; /**
* @author Tim
*
* 2019年4月24日
*
* mybatis 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 MybatisInterceptor implements Interceptor {
private static final Logger log = Logger.getLogger(MybatisInterceptor.class);
@Override
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];
}
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Configuration configuration = mappedStatement.getConfiguration();
Object returnVal = invocation.proceed();
//获取sql语句
String sql = getSql(configuration, boundSql);
log.info("#####拦截器获取SQL#### "+sql);
     //统计SQL执行时间
     Object target = invocation.getTarget();
     Object result = null;
     if (target instanceof Executor) {
       long start = System.currentTimeMillis();
            Method method = invocation.getMethod();
/**执行方法*/
result = invocation.proceed();
long end = System.currentTimeMillis();
logger.info("[" + method.getName() + "] 耗时 [" + (end - start) + "] ms");
}
    return returnVal;
    }

    @Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} @Override
public void setProperties(Properties arg0) {
} /**
* 获取SQL
* @param configuration
* @param boundSql
* @return
*/
private String getSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (parameterObject == null || parameterMappings.size() == 0) {
return sql;
}
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;
} private 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(obj) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}
}
 
 

  

最新文章

  1. [DBW]一个小巧的Class方案
  2. Android中动画
  3. linux mmap 内存映射【转】
  4. baidu 快递查询API
  5. iOS应用架构谈 本地持久化方案及动态部署
  6. SharePoint表单和工作流 - Nintex篇(二)
  7. MySQL加载并执行SQL脚本文件
  8. Cocos2d-x 3.2 大富翁游戏项目开发-第八部分 角色的散步路径
  9. 【转】JDBC学习笔记(5)——利用反射及JDBC元数据编写通用的查询方法
  10. iptables实用教程(一):基本概念和原理
  11. Algorithm --&gt; 动态规划
  12. connection holder is null新增解决方案(2018-06-02)
  13. Virtualbox 虚拟机安装Linux
  14. vue 之webpack打包工具的使用
  15. vue 中如何对公共css、 js 方法进行单文件统一管理,全局调用
  16. Arcgis发布服务
  17. Confluence 6 从外部目录中同步数据手动同步缓存
  18. Nginx(二):虚拟主机配置
  19. Ubuntu 14.04 设置Android开发环境
  20. EKF model&amp;realization

热门文章

  1. elasticsearch堆内存的配置建议
  2. nodejs工作大全
  3. mui初级入门教程(六)— 模板页面实现原理及多端适配指南
  4. 用 MuGo 搭建 Go Engine 在 KGS 对战
  5. hive_action
  6. Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file.
  7. flask_sqlalchemy获取动态 model名称 和 动态查询
  8. prometheus linux系统告警规则 实例
  9. 应用安全 - 渗透测试 - .net网站
  10. python基础-4.1 open 打开文件练习:修改haproxy配置文件