电脑疯子技术论坛|电脑极客社区

微信扫一扫 分享朋友圈

已有 2006 人浏览分享

MyBatis集成P6Spy显示实际的SQL(代码教程)

[复制链接]
2006 0

在应用程序开发过程中,为了方便调试,通常都需要知道在DAO层,
程序执行的SQL是什么,而P6spy这个组件正是提供了该功能。

接下来将详细介绍P6Spy的详细使用。

一 系统集成P6spy

1 添加依赖

  1. <properties>
  2.         <p6spy.version>3.6.0</p6spy.version>
  3.         <druid.version>1.1.6</druid.version>
  4.     </properties>

  5.   <dependency>
  6.             <groupid>p6spy</groupid>
  7.             p6spy</artifactid>
  8.             <version>${p6spy.version}</version>
  9.         </dependency>

  10.         <dependency>
  11.             <groupid>com.alibaba</groupid>
  12.             druid</artifactid>
  13.             <version>${druid.version}</version>
  14.         </dependency>
复制代码


2 实现自定义的SQL输出格式

为了输出的内容足够的简洁,这里只保留了当期那时间,执行SQL的耗时以及执行的SQL语句

  1. package net.ittimeline.mybatis.practices.core;
  2. import com.alibaba.druid.sql.SQLUtils;
  3. import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
  4. /**
  5. * @author tony ittimeline@163.com
  6. * @date 2018-01-30-下午10:45
  7. * @website wwww.ittimeline.net
  8. * @see
  9. * @since JDK8u162
  10. */
  11. public class CustomizeLineFormat implements MessageFormattingStrategy {

  12.     public String buildMessage(String now, long elapsed, String sql) {
  13.         StringBuffer content = new StringBuffer();
  14.         if (org.apache.commons.lang3.StringUtils.isNotEmpty(now) && org.apache.
  15. commons.lang3.StringUtils.isNotEmpty(Long.valueOf(elapsed).toString())
  16.                 && org.apache.commons.lang3.StringUtils.isNotEmpty(sql)) {
  17.             content.append("当前时间:" + now);
  18.             content.append(" SQL执行耗时(毫秒)为" + elapsed);
  19.             content.append(" SQL执行的语句是\n" + SQLUtils.formatMySql(sql)+"\n\n");
  20.         }
  21.         return content.toString();
  22.     }

  23.     @Override
  24.     public String formatMessage(int connectionId, String now, l
  25. ong elapsed, String category, String prepared, String sql) {
  26.         return buildMessage(now, elapsed, sql);
  27.     }

  28. }
复制代码


3 配置spy.properties

该文件只需要配置

modulelist,logfile,logMessageFormat,dateformat即可。

  1. ###
  2. # #%L
  3. # P6Spy
  4. # %%
  5. # Copyright (C) 2013 P6Spy
  6. # %%
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. #      https://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. # #L%
  19. ###

  20. #################################################################
  21. # P6Spy Options File                                            #
  22. # See documentation for detailed instructions                   #
  23. # https://p6spy.github.io/p6spy/2.0/configandusage.html          #
  24. #################################################################

  25. #################################################################
  26. # MODULES                                                       #
  27. #                                                               #
  28. # Module list adapts the modular functionality of P6Spy.        #
  29. # Only modules listed are active.                               #
  30. # (default is com.p6spy.engine.logging.P6LogFactory and         #
  31. # com.p6spy.engine.spy.P6SpyFactory)                            #
  32. # Please note that the core module (P6SpyFactory) can't be      #
  33. # deactivated.                                                  #
  34. # Unlike the other properties, activation of the changes on     #
  35. # this one requires reload.                                     #
  36. #################################################################
  37. #modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.
  38. P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
  39. modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P
  40. 6LogFactory,com.p6spy.engine.outage.P6OutageFactory
  41. ################################################################
  42. # CORE (P6SPY) PROPERTIES                                      #
  43. ################################################################

  44. # A comma separated list of JDBC drivers to load and register.
  45. # (default is empty)
  46. #
  47. # Note: This is normally only needed when using P6Spy in an
  48. # application server environment with a JNDI data source or when
  49. # using a JDBC driver that does not implement the JDBC 4.0 API
  50. # (specifically automatic registration).
  51. #driverlist=
  52. #url="jdbc:p6spy:oracle:thin:@localhost:1521:orcl" \u5176\u4e2d\u7684p6spy\u5fc5\u9
  53. 87b\u8981\uff0c\u56e0\u4e3a\u8fd9\u6837\u624d\u4f1a\u88ab\u62e6\u622a
  54. #drive=com.p6spy.engine.spy.P6SpyDriver
  55. driverlist=com.mysql.jdbc.Driver
  56. # for flushing per statement
  57. # (default is false)
  58. #autoflush = false


  59. # prints a stack trace for every statement logged
  60. #stacktrace=false
  61. # if stacktrace=true, specifies the stack trace to print
  62. #stacktraceclass=

  63. # determines if property file should be reloaded
  64. # Please note: reload means forgetting all the previously set
  65. # settings (even those set during runtime - via JMX)
  66. # and starting with the clean table
  67. # (default is false)
  68. #reloadproperties=false

  69. # determines how often should be reloaded in seconds
  70. # (default is 60)
  71. #reloadpropertiesinterval=60

  72. # specifies the appender to use for logging
  73. # Please note: reload means forgetting all the previously set
  74. # settings (even those set during runtime - via JMX)
  75. # and starting with the clean table
  76. # (only the properties read from the configuration file)
  77. # (default is com.p6spy.engine.spy.appender.FileLogger)
  78. #appender=com.p6spy.engine.spy.appender.Slf4JLogger
  79. #appender=com.p6spy.engine.spy.appender.StdoutLogger

  80. #appender=com.p6spy.engine.spy.appender.FileLogger

  81. # name of logfile to use, note Windows users should make sure to use
  82. forward slashes in their pathname (e:/test/spy.log)
  83. # (used for com.p6spy.engine.spy.appender.FileLogger only)
  84. # (default is spy.log)
  85. #logfile = spy.log
  86. #windows \u7528\u6237\u8bf7\u7528 C:/spy.log \u683c\u5f0f\uff0c\u4e0d\u8981\u7528\
  87. logfile=mybatis-practices-core.log

  88. # append to the p6spy log file. if this is set to false the
  89. # log file is truncated every time. (file logger only)
  90. # (default is true)
  91. \uff03\u8ffd\u52a0\u5230 p6spy \u65e5\u5fd7\u6587\u4ef6\u300
  92. 2\u5982\u679c\u8bbe\u7f6e\u4e3afalse
  93. \uff03\u65e5\u5fd7\u6587\u4ef6\u88ab\u622a\u65ad\u6bcf\u6b21\u3002 \uff0
  94. 8\u53ea\u9650\u4e8e\u6587\u4ef6\u8bb0\u5f55\u5668\uff09
  95. \uff03\uff08\u9ed8\u8ba4\u4e3atrue\uff09
  96. #append=true

  97. # class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)
  98. #\u591a\u884c\u8f93\u51fa\u4e3a com.p6spy.engine.spy.appender.MultiLineFormat
  99. #\u884c\u7684\u65f6\u95f4\u683c\u5f0f\u5316\u914d\u7f6e\u5728 dateformat \u8bbe\u5b9a
  100. #current time|execution time|category|connection id|statement SQL String|effective SQL string
  101. #\u65e5\u5fd7\u683c\u5f0f\u4e3a \u5f53\u524d\u65f6\u95f4\u6233|\u6267\u884c\u8
  102. bed\u53e5\u82b1\u8d39\u7684\u65f
  103. 6\u95f4|\u8c03\u7528\u7684\u7c7b\u522b|connectionId|\u58f0\u660eSQL\u5b57\u7
  104. b26\u4e32|\u6709\u6548\u7684SQL\u5b57\u7b26\u4e32
  105. #logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
  106. logMessageFormat= net.ittimeline.mybatis.practices.core.CustomizeLineFormat

  107. # format that is used for logging of the date/time/... (has to be compatible with java.text.SimpleDateFormat)
  108. # (default is dd-MMM-yy)
  109. databaseDialectDateFormat=yyyy-MM-dd HH:mm:ss

  110. # sets the date format using Java's SimpleDateFormat routine.
  111. # In case property is not set, miliseconds since 1.1.1970 (unix time) is used (default is empty)
  112. #dateformat=
  113. dateformat=yyyy-MM-dd HH:mm:ss

  114. # whether to expose options via JMX or not
  115. # (default is true)
  116. #jmx=true

  117. # if exposing options via jmx (see option: jmx), what should be the prefix used?
  118. # jmx naming pattern constructed is: com.p6spy(.<jmxprefix>)?:name=<optionsclassname>
  119. # please note, if there is already such a name in use it would b
  120. e unregistered first (the last registered wins)
  121. # (default is none)
  122. #jmxPrefix=

  123. #################################################################
  124. # DataSource replacement                                        #
  125. #                                                               #
  126. # Replace the real DataSource class in your application server  #
  127. # configuration with the name com.p6spy.engine.spy.P6DataSource #
  128. # (that provides also connection pooling and xa support).       #
  129. # then add the JNDI name and class name of the real             #
  130. # DataSource here                                               #
  131. #                                                               #
  132. # Values set in this item cannot be reloaded using the          #
  133. # reloadproperties variable. Once it is loaded, it remains      #
  134. # in memory until the application is restarted.                 #
  135. #                                                               #
  136. #################################################################
  137. #realdatasource=/RealMySqlDS
  138. #realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource

  139. #################################################################
  140. # DataSource properties                                         #
  141. #                                                               #
  142. # If you are using the DataSource support to intercept calls    #
  143. # to a DataSource that requires properties for proper setup,    #
  144. # define those properties here. Use name value pairs, separate  #
  145. # the name and value with a semicolon, and separate the         #
  146. # pairs with commas.                                            #
  147. #                                                               #
  148. # The example shown here is for mysql                           #
  149. #                                                               #
  150. #################################################################
  151. #realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar

  152. #################################################################
  153. # JNDI DataSource lookup                                        #
  154. #                                                               #
  155. # If you are using the DataSource support outside of an app     #
  156. # server, you will probably need to define the JNDI Context     #
  157. # environment.                                                  #
  158. #                                                               #
  159. # If the P6Spy code will be executing inside an app server then #
  160. # do not use these properties, and the DataSource lookup will   #
  161. # use the naming context defined by the app server.             #
  162. #                                                               #
  163. # The two standard elements of the naming environment are       #
  164. # jndicontextfactory and jndicontextproviderurl. If you need    #
  165. # additional elements, use the jndicontextcustom property.      #
  166. # You can define multiple properties in jndicontextcustom,      #
  167. # in name value pairs. Separate the name and value with a       #
  168. # semicolon, and separate the pairs with commas.                #
  169. #                                                               #
  170. # The example shown here is for a standalone program running on #
  171. # a machine that is also running JBoss, so the JDNI context     #
  172. # is configured for JBoss (3.0.4).                              #
  173. #                                                               #
  174. # (by default all these are empty)                              #
  175. #################################################################
  176. #jndicontextfactory=org.jnp.interfaces.NamingContextFactory
  177. #jndicontextproviderurl=localhost:1099
  178. #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.nameing:org.jnp.interfaces

  179. #jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory
  180. #jndicontextproviderurl=iiop://localhost:900

  181. ################################################################
  182. # P6 LOGGING SPECIFIC PROPERTIES                               #
  183. ################################################################

  184. # filter what is logged
  185. # please note this is a precondition for usage of: include/exclude/sqlexpression
  186. # (default is false)
  187. #filter=false

  188. # comma separated list of strings to include
  189. # please note that special characters escaping (used in java)
  190. has to be done for the provided regular expression
  191. # (default is empty)
  192. #include =
  193. # comma separated list of strings to exclude
  194. # (default is empty)
  195. #exclude =

  196. # sql expression to evaluate if using regex
  197. # please note that special characters escaping (used in java) has
  198. to be done for the provided regular expression
  199. # (default is empty)
  200. #sqlexpression =

  201. #list of categories to exclude: error, info, batch, debug, statement,
  202. #commit, rollback and result are valid values
  203. # (default is info,debug,result,resultset,batch)
  204. #excludecategories=info,debug,result,resultset,batch

  205. # Execution threshold applies to the standard logging of P6Spy.
  206. # While the standard logging logs out every statement
  207. # regardless of its execution time, this feature puts a time
  208. # condition on that logging. Only statements that have taken
  209. # longer than the time specified (in milliseconds) will be
  210. # logged. This way it is possible to see only statements that
  211. # have exceeded some high water mark.
  212. # This time is reloadable.
  213. #
  214. # executionThreshold=integer time (milliseconds)
  215. # (default is 0)
  216. #executionThreshold=

  217. ################################################################
  218. # P6 OUTAGE SPECIFIC PROPERTIES                                #
  219. ################################################################
  220. # Outage Detection
  221. #
  222. # This feature detects long-running statements that may be indicative of
  223. # a database outage problem. If this feature is turned on, it will log any
  224. # statement that surpasses the configurable time boundary during its execution.
  225. # When this feature is enabled, no other statements are logged except the long
  226. # running statements. The interval property is the boundary time set in seconds.
  227. # For example, if this is set to 2, then any statement requiring at least 2
  228. # seconds will be logged. Note that the same statement will continue to be logged
  229. # for as long as it executes. So if the interval is set to 2, and the query takes
  230. # 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).
  231. #
  232. # outagedetection=true|false
  233. # outagedetectioninterval=integer time (seconds)
  234. #
  235. # (default is false)
  236. #outagedetection=false
  237. # (default is 60)
  238. #outagedetectioninterval=30</optionsclassname></jmxprefix>
复制代码


二 MyBatis集成P6spy

MyBatis集成P6spy,这里倒不如说成DataSource集成P6Spy更贴切,
这里增加一个名为database.properties的文件,内容如下

  1. jdbc.driver=com.p6spy.engine.spy.P6SpyDriver
  2. jdbc.url=jdbc:p6spy:mysql://127.0.0.1:3306/mybatis?useUnicode=
  3. true&characterEncoding=UTF-8&useSSL=false
  4. jdbc.username=root
  5. jdbc.password=guanglei
复制代码

主要包含了数据库的连接信息,和之前的配置不同的是更换了驱动实现以及数据库连接地址。
而mybatis-config.xml文件中只需要增加一行配置,然后就可以采用${属性名}的方式获取数据库配置了,
配置如下所示

  1. <!--?xml version="1.0" encoding="UTF-8" ?-->
  2. <configuration>
  3.     <properties resource="database.properties"
  4.     <!--配置数据库连接信息 -->
  5.     <environments default="development">
  6.         <environment id="development">
  7.             <transactionmanager type="JDBC"></transactionmanager>
  8.             <datasource type="POOLED">
  9.                 <property name="driver" value="${jdbc.driver}">
  10.                 <property name="url" value="${jdbc.url}">
  11.                 <property name="username" value="${jdbc.username}">
  12.                 <property name="password" value="${jdbc.password}">
  13.             </property></property></property></property></datasource>
  14.         </environment>
  15.     </environments>
  16. </properties></configuration>
复制代码


然后运行ContryMapperTest.selectAll()方法,会发现在模块的根路径下
存在一个mybatis-practices-core.log的文件,内容如下

  1. 当前时间:2018-01-30 23:03:07 SQL执行耗时(毫秒)为0 SQL执行的语句是
  2. SELECT country_id AS countryId, country_name AS countryName, country_code AS countryCode
  3. FROM t_country
复制代码




您需要登录后才可以回帖 登录 | 注册

本版积分规则

1

关注

0

粉丝

9021

主题
精彩推荐
热门资讯
网友晒图
图文推荐

Powered by Pcgho! X3.4

© 2008-2022 Pcgho Inc.