spring+mybatis+log4j 输出SQL
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的更多相关文章
- Spring+MyBatis框架中sql语句的书写,数据集的传递以及多表关联查询
在很多Java EE项目中,Spring+MyBatis框架经常被用到,项目搭建在这里不再赘述,现在要将的是如何在项目中书写,增删改查的语句,如何操作数据库,以及后台如何获取数据,如何进行关联查询,以 ...
- SSM环境下配置log4j输出sql和异常到控制台和本地日志文件中
1.引入日志依赖包 <!--解决Spring使用slf4j输出日志与log4j冲突的问题--> <dependency> <groupId>org.slf4j< ...
- ibatis配置log4j输出sql日志信息
为了在开发过程更加直观,我们需要将ibatis日志打开以便观察ibatis运作的细节. ibatis采用Apache common_logging,并结合Apache log4j作为日志输出组件. 在 ...
- hibernate log4j 输出sql
applicationContext.xml <bean id="sessionFactory" class="org.springframework ...
- mybatis 测试输出SQL语句到控制台配置
1: mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...
- 【原】配置Log4j,使得MyBatis打印出SQL语句
[环境参数] JDK:jdk1.8.0_25 IDE:Eclipse Luna Servie Release 1 框架:Spring 4.1.5 + SpringMVC 4.1.5 + MyBatis ...
- MyBatis3 用log4j在控制台输出 SQL
用log4j在控制台输出 SQL 在spring-mybatis.xml中配置 <bean id="sqlSessionFactory" class="org.my ...
- mybatis和redis整合 log4j打印sql语句
首先,需要在项目中引进jedis-2.8.1.jar包,在pom.xml里加上 <dependency> <groupId>redis.clients</groupId& ...
- Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource
前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-MybatisDAO文件解析(二) 首先了解下sql mapper的动态sql语法 具体的动态sql的 ...
随机推荐
- [Codeforces 274E]:Mirror Room(模拟)
题目传送门 题目描述 有一个$n\times m$的格子图,其中有一些是黑色的,另一些为白色.从某个白色格子的中心点向左上($NW$),左下($SW$),右上($NE$),右下($SE$)四个方向中的 ...
- 移动端与PHP服务端接口通信流程设计(基础版)
转载自:http://blog.snsgou.com/post-766.html --->非开放性平台 --->公司内部产品 接口特点汇总: 1.因为是非开放性的,所以所有的接口都是封闭的 ...
- WCF - Hosting WCF Service 四种托管方式
https://www.tutorialspoint.com/wcf/wcf_hosting_service.htm After creating a WCF service, the next st ...
- 玩转visual studio系列之类设计图
类设计图 vs 类设计图 微软 安装好vs2017后,在打开的IDE中,随便选择一个文件夹创建[类图],却发现没有该选项 类图辅助器 解决方案 1.点击[工具]选项卡,在下拉的菜单中选择第一项 获取 ...
- Linux双网卡绑定和解除
转载双网卡绑定和解除 一定要在服务管理中关闭NetworkManager服务并禁用自动启动,因为NetworkManager服务是实时生效的,一旦设置错,管理员就得回到机房接显示器配置网络连接. 以 ...
- java valueOf
valueOf 方法可以将原生数值类型转化为对应的Number类型,java.lang.Number 基类包括ouble.Float.Byte.Short.Integer 以及 Long派生类, 也可 ...
- 用Vue来实现音乐播放器(六):JSONP的封装
在npm上下载jsonp的包 这个包的用法 传入的参数是地址加上地址参数的混合 但是想封装一个将地址和地址参数分别传入的jsonp方法 所以来封装一个 import originJSONP from ...
- LDA提取信息
文本主题模型提取 如下程序将句子主题提取后,将权重值存入dataframe. #!/usr/bin/python # -*- coding:utf-8 -*- import pandas as pd ...
- 《计算机程式设计》Week4 课堂笔记
本笔记记录自 Coursera课程 <计算机程式设计> 台湾大学 刘邦锋老师 Week4 Functions 4-1 System Function 函数主要分为两大类系统定义函数与使用者 ...
- Nginx主要功能及使用
Nginx配置详解 序言 Nginx是lgor Sysoev为俄罗斯访问量第二的rambler.ru站点设计开发的.从2004年发布至今,凭借开源的力量,已经接近成熟与完善. Nginx功能丰富, ...