1、显示出sql内容:

新建2个类:
MybatisInterceptor ;拦截sql,并获得输出sql内容

  1. package com.cpp.core.filter;
  2. import java.text.DateFormat;
  3. import java.util.Date;
  4. import java.util.List;
  5. import java.util.Locale;
  6. import java.util.Properties;
  7. import org.apache.ibatis.executor.Executor;
  8. import org.apache.ibatis.mapping.BoundSql;
  9. import org.apache.ibatis.mapping.MappedStatement;
  10. import org.apache.ibatis.mapping.ParameterMapping;
  11. import org.apache.ibatis.plugin.Interceptor;
  12. import org.apache.ibatis.plugin.Intercepts;
  13. import org.apache.ibatis.plugin.Invocation;
  14. import org.apache.ibatis.plugin.Plugin;
  15. import org.apache.ibatis.plugin.Signature;
  16. import org.apache.ibatis.reflection.MetaObject;
  17. import org.apache.ibatis.session.Configuration;
  18. import org.apache.ibatis.session.ResultHandler;
  19. import org.apache.ibatis.session.RowBounds;
  20. import org.apache.ibatis.type.TypeHandlerRegistry;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import com.cpp.core.common.utils.SQLFormatter;
  24. @Intercepts({
  25. @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
  26. @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
  27. RowBounds.class, ResultHandler.class }) })
  28. public class MybatisInterceptor implements Interceptor {
  29. private static Logger logger = LoggerFactory.getLogger(MybatisInterceptor.class);
  30. private Properties properties;
  31. public Object intercept(Invocation invocation) throws Throwable {
  32. MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
  33. Object parameter = null;
  34. if (invocation.getArgs().length > 1) {
  35. parameter = invocation.getArgs()[1];
  36. }
  37. String sqlId = mappedStatement.getId();
  38. BoundSql boundSql = mappedStatement.getBoundSql(parameter);
  39. Configuration configuration = mappedStatement.getConfiguration();
  40. Object returnValue = null;
  41. long start = System.currentTimeMillis();
  42. returnValue = invocation.proceed();
  43. long end = System.currentTimeMillis();
  44. long time = (end - start);
  45. if (time > 1) {
  46. String sql = getSql(configuration, boundSql, sqlId, time);
  47. logger.info("调用的java方法为:\n "+sql.split(":")[0]);
  48. logger.info("查询sql语句为:\n"+SQLFormatter.format(sql.split(":")[1]) +"\n"+"sql语句执行的时间:"+time+"\n\n");
  49. }
  50. return returnValue;
  51. }
  52. public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId, long time) {
  53. String sql = showSql(configuration, boundSql);
  54. StringBuilder str = new StringBuilder(100);
  55. str.append(sqlId);
  56. str.append(":");
  57. str.append(sql);
  58. str.append(":");
  59. str.append(time);
  60. str.append("ms");
  61. return str.toString();
  62. }
  63. private static String getParameterValue(Object obj) {
  64. String value = null;
  65. if (obj instanceof String) {
  66. value = "'" + obj.toString() + "'";
  67. } else if (obj instanceof Date) {
  68. DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
  69. value = "'" + formatter.format(new Date()) + "'";
  70. } else {
  71. if (obj != null) {
  72. value = obj.toString();
  73. } else {
  74. value = "";
  75. }
  76. }
  77. return value;
  78. }
  79. public static String showSql(Configuration configuration, BoundSql boundSql) {
  80. Object parameterObject = boundSql.getParameterObject();
  81. List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  82. String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
  83. if (parameterMappings.size() > 0 && parameterObject != null) {
  84. TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  85. if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
  86. sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
  87. } else {
  88. MetaObject metaObject = configuration.newMetaObject(parameterObject);
  89. for (ParameterMapping parameterMapping : parameterMappings) {
  90. String propertyName = parameterMapping.getProperty();
  91. if (metaObject.hasGetter(propertyName)) {
  92. Object obj = metaObject.getValue(propertyName);
  93. sql = sql.replaceFirst("\\?", getParameterValue(obj));
  94. } else if (boundSql.hasAdditionalParameter(propertyName)) {
  95. Object obj = boundSql.getAdditionalParameter(propertyName);
  96. sql = sql.replaceFirst("\\?", getParameterValue(obj));
  97. }
  98. }
  99. }
  100. }
  101. return sql;
  102. }
  103. public Object plugin(Object target) {
  104. return Plugin.wrap(target, this);
  105. }
  106. public void setProperties(Properties properties0) {
  107. this.properties = properties0;
  108. }
  109. }

2、在新建sql格式化工具,格式化sql语句

  1. package com.cpp.core.filter;
  2. import java.util.Properties;
  3. import org.apache.ibatis.executor.Executor;
  4. import org.apache.ibatis.mapping.MappedStatement;
  5. import org.apache.ibatis.plugin.Interceptor;
  6. import org.apache.ibatis.plugin.Intercepts;
  7. import org.apache.ibatis.plugin.Invocation;
  8. import org.apache.ibatis.plugin.Plugin;
  9. import org.apache.ibatis.plugin.Signature;
  10. import org.apache.ibatis.session.ResultHandler;
  11. import org.apache.ibatis.session.RowBounds;
  12. @Intercepts({
  13. @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
  14. @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
  15. RowBounds.class, ResultHandler.class }) })
  16. public class SqlStatementInterceptor implements Interceptor{
  17. private Properties properties;
  18. @Override
  19. public Object intercept(Invocation invocation) throws Throwable {
  20. System.out.println("test");
  21. return invocation.proceed();
  22. }
  23. @Override
  24. public Object plugin(Object target) {
  25. return Plugin.wrap(target, this);
  26. }
  27. @Override
  28. public void setProperties(Properties properties0) {
  29. this.properties = properties0;
  30. }
  31. }

3、在spring的配置文件中添加

  1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  2. <property name="dataSource" ref="dataSource" />
  3. <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
  4. <property name="typeAliasesPackage" value="com.cpp.core" />
  5. <!-- 显式指定Mapper文件位置 -->
  6. <property name="mapperLocations" value="classpath:/mybatis/*/*Mapper.xml" />
  7. <property name="plugins">
  8. <array>
  9. <ref bean="paginationInterceptor"/>
  10. <ref bean="sqlStatementInterceptor"/>
  11. </array>
  12. </property>
  13. <property name="configurationProperties">
  14. <props>
  15. <prop key="dialect">mysql</prop>
  16. </props>
  17. </property>
  18. </bean>

配置插件

  1. <ref bean="sqlStatementInterceptor"/>

配置注入的内容

  1. <bean id="sqlStatementInterceptor" class="com.cpp.core.filter.MybatisInterceptor"></bean>

2、如果使用的是Druid来连接的数据库


在web.xml文件中添加下面的信息

  1. <servlet>
  2. <servlet-name>DruidStatView</servlet-name>
  3. <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>DruidStatView</servlet-name>
  7. <url-pattern>/druid/*</url-pattern>
  8. </servlet-mapping>
  9.  
  10. 可以通过web的访问的形式进行访问页面:输入:
    http://dev.eop.zhc360.com:8080/cpp-middleman-api/druid/sql.html

mybatis使用拦截器显示sql,使用druid配置连接信息的更多相关文章

  1. MyBatis实现拦截器分页功能

    1.原理 在mybatis使用拦截器(interceptor),截获所执行方法的sql语句与参数. (1)修改sql的查询结果:将原sql改为查询count(*) 也就是条数 (2)将语句sql进行拼 ...

  2. Mybatis Interceptor 拦截器原理 源码分析

    Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最 ...

  3. mybatis Interceptor拦截器代码详解

    mybatis官方定义:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...

  4. Mybatis之拦截器原理(jdk动态代理优化版本)

    在介绍Mybatis拦截器代码之前,我们先研究下jdk自带的动态代理及优化 其实动态代理也是一种设计模式...优于静态代理,同时动态代理我知道的有两种,一种是面向接口的jdk的代理,第二种是基于第三方 ...

  5. Mybatis利用拦截器做统一分页

    mybatis利用拦截器做统一分页 查询传递Page参数,或者传递继承Page的对象参数.拦截器查询记录之后,通过改造查询sql获取总记录数.赋值Page对象,返回. 示例项目:https://git ...

  6. mybatis定义拦截器

    applicationContext.xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlS ...

  7. Mybatis自定义拦截器与插件开发

    在Spring中我们经常会使用到拦截器,在登录验证.日志记录.性能监控等场景中,通过使用拦截器允许我们在不改动业务代码的情况下,执行拦截器的方法来增强现有的逻辑.在mybatis中,同样也有这样的业务 ...

  8. SpringMVC利用拦截器防止SQL注入

    引言 随着互联网的发展,人们在享受互联网带来的便捷的服务的时候,也面临着个人的隐私泄漏的问题.小到一个拥有用户系统的小型论坛,大到各个大型的银行机构,互联网安全问题都显得格外重要.而这些网站的背后,则 ...

  9. struts2拦截器interceptor的三种配置方法

    1.struts2拦截器interceptor的三种配置方法 方法1. 普通配置法 <struts> <package name="struts2" extend ...

随机推荐

  1. 【转】Swig使用指南

    如何使用 API swig.init({ allowErrors: false, autoescape: true, cache: true, encoding: 'utf8', filters: { ...

  2. 使用n g r o k将本地主机URL暴露给互联网

    在本地开发对接第三方服务的时候,对方有的时候会要求我们提供一个线上的URL地址.例如微信登录 1.下载ngrok https://ngrok.com/download 顺便注册一个账号(使用GitHu ...

  3. 区别script中的type=”text/javascript”和language=”Javascript”

    内容提要 在制作网页的时候,往往需要在页面中使用客户端能够运行的JS代码,因此,都需要添加引用.JS引用一般有type="text/javascript"和language=&qu ...

  4. Cordova - Windows版本图形界面管理工具,告别命令行输入方式!

    Cordova本身提供的是命令行管理工具,并没有提供图形界面管理工具,虽然命令行管理工具可以完成所有Cordova管理,但是对于我这种懒蛋,可真不希望每次都输入命令,而且我更担心一旦输错一个字符,命令 ...

  5. 《Python黑帽子:黑客与渗透测试编程之道》 Scapy:网络的掌控者

    窃取email认证: 测试代码: #!/usr/bin/python #coding=utf-8 from scapy.all import * #数据包回调函数 def packet_callbac ...

  6. Mysql分析-profile详解

    一.前言当我们要对某一条sql的性能进行分析时,可以使用它. Profiling是从 mysql5.0.3版本以后才开放的.启动profile之后,所有查询包括错误的语句都会记录在内.关闭会话或者se ...

  7. Google Guava 类库简介

    Guava 是一个 Google开发的 基于java的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency librar ...

  8. 【Hight Performance Javascript】——脚本加载和运行

    脚本加载和运行 当浏览器遇到一个<script>标签时,无法预知javascript是否在<p>标签中添加内容.因此,浏览器停下来,运行javascript代码,然后继续解析. ...

  9. python 初步认识Flask

    1.简介 flask 问题一:  访问百度的流程? a. 客户端: 发送请求报文,  请求行, 请求头, 请求体 b.服务端: 解析请求的报文, 解析域名, 进行路由匹配分发找到对应的视图函数, 打包 ...

  10. Debian&&ubuntu系安装MegaCli

    MegaCli这个命令可以用来监控raid状态.磁盘状况等,最近上了一批ubuntu系统跑openstack,问题是MegaCli在官网上只有rpm格式的包,没有deb的包,但是还是有办法解决的,rp ...