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的 ...
随机推荐
- 为什么Redis可以方便地实现分布式锁
1.Redis为单进程单线程模式,采用队列模式将并发访问变成串行访问,且多客户端对Redis的连接并不存在竞争关系. 2.Redis的SETNX命令可以方便的实现分布式锁. setNX(SET if ...
- VS 2010内存泄漏检测
控制台程序在启动时调用 _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); 程序正常退出后会打印内存泄漏信息. MFC程序不用 ...
- The MEAN stack is a modern replacement for the LAMP (Linux, Apache, MySQL, PHP/Python) stack
w https://www.mongodb.com/blog/post/building-your-first-application-mongodb-creating-rest-api-using- ...
- 使用spring配置类代替xml配置文件注册bean类
spring配置类,即在类上加@Configuration注解,使用这种配置类来注册bean,效果与xml文件是完全一样的,只是创建springIOC容器的方式不同: //通过xml文件创建sprin ...
- 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_08 转换流_2_编码引出的问题_FileReader读取GBK格式文件
IDEA默认的编码格式是UTF-8 新建一个txt文件.输入你好 ANSI就是系统默认编码.保存即可. 通过IDE打开是乱码的,因为默认打开的方式是UTF-8 转换为char类型 输出了乱码
- 类Thread
public final void join() throws InterruptedException /* * public final void join() * throws Interrup ...
- 【GTS】关于GtsTetheringTestCases模块的几个失败项
GTS---关于GtsTetheringTestCases模块的几个失败项 1.run gts -m GtsTetheringTestCases -t com.google.android.tethe ...
- 阿里云SLB产品HTTP、HTTPS、UDP协议使用
1.http协议测试 第一步:添加http监听服务,前端端口为8080,后端端口为80,健康检查中检查端口为后端端口80: 第二步:在绑定的服务器上安装服务,步骤如下 centos系统中启动http协 ...
- 神器 工具 推荐 SRDebugger
unity asset store 关联下载 ,添加这个书签 javascript:var url = window.location.href;var id = url.substr(url.la ...
- codeforces#1215E. Marbles(状压DP)
题目大意:给出一个由N个整数组成的序列,通过每次交换相邻的两个数,使这个序列的每个相同的数都相邻.求最小的交换次数. 比如给出序列:1 2 3 2 1 ,那么最终序列应该是 1 1 2 2 3 ,最小 ...