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;
}
}
 
 

  

spring+mybatis+log4j 输出SQL的更多相关文章

  1. Spring+MyBatis框架中sql语句的书写,数据集的传递以及多表关联查询

    在很多Java EE项目中,Spring+MyBatis框架经常被用到,项目搭建在这里不再赘述,现在要将的是如何在项目中书写,增删改查的语句,如何操作数据库,以及后台如何获取数据,如何进行关联查询,以 ...

  2. SSM环境下配置log4j输出sql和异常到控制台和本地日志文件中

    1.引入日志依赖包 <!--解决Spring使用slf4j输出日志与log4j冲突的问题--> <dependency> <groupId>org.slf4j< ...

  3. ibatis配置log4j输出sql日志信息

    为了在开发过程更加直观,我们需要将ibatis日志打开以便观察ibatis运作的细节. ibatis采用Apache common_logging,并结合Apache log4j作为日志输出组件. 在 ...

  4. hibernate log4j 输出sql

    applicationContext.xml <bean id="sessionFactory"        class="org.springframework ...

  5. mybatis 测试输出SQL语句到控制台配置

    1: mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...

  6. 【原】配置Log4j,使得MyBatis打印出SQL语句

    [环境参数] JDK:jdk1.8.0_25 IDE:Eclipse Luna Servie Release 1 框架:Spring 4.1.5 + SpringMVC 4.1.5 + MyBatis ...

  7. MyBatis3 用log4j在控制台输出 SQL

    用log4j在控制台输出 SQL 在spring-mybatis.xml中配置 <bean id="sqlSessionFactory" class="org.my ...

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

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

  9. Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource

    前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-MybatisDAO文件解析(二) 首先了解下sql mapper的动态sql语法 具体的动态sql的 ...

随机推荐

  1. jquery.ui.widget.js

  2. Laravel 的Artisan 命令学习

    Laravel 的Artisan 命令学习 Artisan 是 Laravel 提供的 CLI(命令行接口),它提供了非常多实用的命令来帮助我们开发 Laravel 应用.前面我们已使用过 Artis ...

  3. 【洛谷P1036 选数】

    这个题显然用到了深搜的内容 让我们跟着代码找思路 #include<bits/stdc++.h>//万能头 ],ans; inline bool prime(int n)//最简单的判定素 ...

  4. PhantomJs 与 Casperjs

    利用PhantomJS做网页截图经济适用,但其API较少,做其他功能就比较吃力了. CasperJs是对phantomjs的一次封装.即phantomjs是原生的,而casperjs是封装在以phan ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_05 IO字符流_5_flush方法和close方法的区别

    flush之后,还可以继续使用流写文件

  6. win10+jdk+mysql+tomcat+jpress环境搭建与部署

    本机搭建jpress用于接口测试的学习 目录 1.环境与工具准备 2.mysql服务端安装 3.tomcat配置 4.jpress部署 1.环境与工具准备 a.服务器为本机为win10 64位 b.j ...

  7. php-fpm启动不起来,php-fpm无法启动的一种情况

    今天碰了一个很奇怪的问题,平时好好的php-fpm修改了一个参数后,突然启动不起来了,试着把参数还原.甚至用备份的配置文件还原都没办法启动php,而且不给任务启动错误的提示,纳闷!!!后来上网找了个资 ...

  8. 20191103 《Spring5高级编程》笔记-第3章

    第3章 在Spring中引入IoC和DI 依赖注入是IOC的一种特殊形式,尽管这两个术语经常可以互换使用. 3.1 控制反转和依赖注入 IOC的核心是DI,旨在提供一种更简单的机制来设置组件依赖项,并 ...

  9. [Git] 004 初识 Git 与 GitHub 之查看历史记录

    在 GitHub 的 UI 界面使用 Git 查看历史纪录 1. 右侧有个 history 2. 点击后跳转页面 3. 点击相应标题(commit 时写的),进入相应版本(历史) 4. 我选择了 I ...

  10. String的相关操作总结

    Java中的String与常量池 string是java中的字符串.String类是不可变的,对String类的任何改变,都是返回一个新的String类对象. string是java中的字符串.Str ...