MyBatis打印SQL执行时间
1、plugins
MyBatis官网对于plugins的描述是这样的:
MyBatis allows you to intercept calls to at certain points within the execution of a mapped statement. By default, MyBatis allows plug-ins to intercept method calls of:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
The details of these classes methods can be discovered by looking at the full method signature of each, and the source code which is available with each MyBatis release. You should understand the behaviour of the method you’re overriding, assuming you’re doing something more than just monitoring calls. If you attempt to modify or override the behaviour of a given method, you’re likely to break the core of MyBatis. These are low level classes and methods, so use plug-ins with caution.
Using plug-ins is pretty simple given the power they provide. Simply implement the Interceptor interface, being sure to specify the signatures you want to intercept.
// ExamplePlugin.java
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
<!-- mybatis-config.xml -->
<plugins>
<plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
</plugin>
</plugins>
The plug-in above will intercept all calls to the "update" method on the Executor instance, which is an internal object responsible for the low level execution of mapped statements.
NOTE Overriding the Configuration Class
In addition to modifying core MyBatis behaviour with plugins, you can also override the Configuration class entirely. Simply extend it and override any methods inside, and pass it into the call to the SqlSessionFactoryBuilder.build(myConfig) method. Again though, this could have a severe impact on the behaviour of MyBatis, so use caution.
2、定义一个Interceptor
package com.cjs.boot.interceptor; import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler; import java.sql.Statement;
import java.util.Properties; @Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})})
public class SqlStatementInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long endTime = System.currentTimeMillis(); StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
sql = sql.replace("\n", "").replace("\t", "").replaceAll("\\s+", " "); log.info("执行SQL: [{}]花费{}ms", sql, (endTime - startTime)); }
} @Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} @Override
public void setProperties(Properties properties) { }
}
2、配置SqlSessionFactory
package com.cjs.boot.config; import com.cjs.boot.interceptor.SqlStatementInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.Resource;
import javax.sql.DataSource; @Configuration
public class MyBatisConfig { @Resource
private DataSource dataSource; @Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setPlugins(new Interceptor[]{new SqlStatementInterceptor()});
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath:mapper/*Mapper.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.cjs.boot.domain.entity");
return sqlSessionFactoryBean.getObject();
} }
3、运行效果
2018-05-09 13:53:55.589 DEBUG 10988 --- [nio-8080-exec-2] c.c.b.m.C.selectByMerchantId : ==> Preparing: SELECT id, merchant_id, coupon_name, coupon_type, par_value, quantity, release_start_time, release_end_time, limit_type, limit_num, remark, create_time, update_time, yn FROM coupon_info WHERE merchant_id = ?
2018-05-09 13:53:55.605 DEBUG 10988 --- [nio-8080-exec-2] c.c.b.m.C.selectByMerchantId : ==> Parameters: 10009(Integer)
2018-05-09 13:53:55.619 DEBUG 10988 --- [nio-8080-exec-2] c.c.b.m.C.selectByMerchantId : <== Total: 0
2018-05-09 13:53:55.620 INFO 10988 --- [nio-8080-exec-2] c.c.b.i.SqlStatementInterceptor : 执行SQL: [SELECT id, merchant_id, coupon_name, coupon_type, par_value, quantity, release_start_time, release_end_time, limit_type, limit_num, remark, create_time, update_time, yn FROM coupon_info WHERE merchant_id = ?]花费15ms
4、补充
4.1、@Signature注解的那几个参数该怎么写
前面文档中说了,可以拦截那四个接口。本例中,我只想拦截查询的SQL,所以我选择拦截StatementHandler的query方法
package org.apache.ibatis.executor.statement; import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.ResultHandler; public interface StatementHandler {
Statement prepare(Connection var1, Integer var2) throws SQLException; void parameterize(Statement var1) throws SQLException; void batch(Statement var1) throws SQLException; int update(Statement var1) throws SQLException; <E> List<E> query(Statement var1, ResultHandler var2) throws SQLException; <E> Cursor<E> queryCursor(Statement var1) throws SQLException; BoundSql getBoundSql(); ParameterHandler getParameterHandler();
}
所以,@Signature注解中,type表示拦截的接口,method表示接口中的方法,而参数就是该方法的参数
4.2、截图

MyBatis打印SQL执行时间的更多相关文章
- mybatis 打印sql 语句
拦截器 package com.cares.asis.mybatis.interceptor; import java.text.DateFormat; import java.util.Date; ...
- mybatis 打印sql log配置
mybatis 打印sql log, 方便调试.如何配置呢? log4j.xml : <!-- 打印sql start --> <appender name="IBatis ...
- 【spring boot】【mybatis】spring boot中mybatis打印sql语句
spring boot中mybatis打印sql语句,怎么打印出来?[参考:https://www.cnblogs.com/sxdcgaq8080/p/9100178.html] 在applicati ...
- 【记录】spring/springboot 配置mybatis打印sql
======================springboot mybatis 打印sql========================================== 方式 一: ##### ...
- mybatis 打印 sql
该文中使用的log框架为logback myBatis3.0.6左右的版本时 打印sql的时候只需要配置如下属性: <logger name="java.sql.Connection& ...
- (后端)SpringBoot中Mybatis打印sql(转)
原文地址:https://www.cnblogs.com/expiator/p/8664977.html 如果使用的是application.properties文件,加入如下配置: logging. ...
- SpringBoot中Mybatis打印sql
原文:https://www.cnblogs.com/expiator/p/8664977.html 如果使用的是application.properties文件,加入如下配置: logging.le ...
- mybatis 打印SQL
如果使用的是application.properties文件,加入如下配置: #打印SQL logging.level.com.jn.ssr.supererscuereporting.dao=debu ...
- logback mybatis 打印sql语句
logbac.xml 文件的基础配置参考的园友的 http://www.cnblogs.com/yuanermen/archive/2012/02/13/2349609.html 然后hibernat ...
随机推荐
- 尚学堂马士兵struts2 课堂笔记(一)
06_尚学堂马士兵_Struts2_Struts2_HelloWorld_5 <constant name="struts.devMode" value="true ...
- Gradle 1.12 翻译——第十八章. 日志
有关其他已翻译的章节请关注Github上的项目:https://github.com/msdx/gradledoc/tree/1.12,或访问:http://gradledoc.qiniudn.com ...
- Chapter 1 Securing Your Server and Network(14):限制功能——xp_cmdshell 和OPENROWSET
原文出处:http://blog.csdn.net/dba_huangzj/article/details/38656615,专题目录:http://blog.csdn.net/dba_huangzj ...
- Socket层实现系列 — I/O事件及其处理函数
主要内容:Socket I/O事件的定义.I/O处理函数的实现. 内核版本:3.15.2 我的博客:http://blog.csdn.net/zhangskd I/O事件定义 sock中定义了几个I/ ...
- pig limit 少于10行,会返回所有记录
my = limit g_log 3; STORE my INTO '/user/wizad/tmp/my' USING PigStorage(','); 这样会返回g_log的所有记录. 要大于等于 ...
- android:background="@color/white" [create file color.xml at res/values/]
<resources><color name="white">#FFFFFF</color><!--白色 --><col ...
- C 语言内存区域分配(进程的各个段)详解
C语言可执行代码结构 名称 内容 代码段 可执行代码.字符串常量 数据段 已初始化全局变量.已初始化全局静态变量.局部静态变量.常量数据 BSS段 未初始化全局变量,未初始化全局静态变量 栈 ...
- Win 32 编程之按钮消息响应(代码小错误修复)
最近不想用MFC写东西了,有没有安装Qt和其他图形化开发环境,只能捣鼓API了.于是乎,就有了以下的学习-- 首先,老套的创建个Windows窗口,由于自己有点小懒,就直接用Hello Word的源码 ...
- 使用MD5加密的登陆demo
最近接手了之前的一个项目,在看里面登陆模块的时候,遇到了一堆问题.现在记录下来. 这个登陆模块的逻辑是这样的 1 首先在登陆之前,调用后台的UserLoginAction类的getRandomKey方 ...
- saiku运行时报错max_length_for_sort_data 需要set higher
infiniDB或者mysql数据库,运行时,按某个字段排序会出错.报错:max_length_for_sort_data ... set higher. saiku报错, 也是这样. 这是数 ...