使用p6spy列印hibernate或者PreparedStatement的帶參數值的sql語句

來源:互聯網
上載者:User

不管在何種環境下用過hibernate的人都知道,哪怕用了show_sql列印出來的sql也是由預留位置號的,預留位置號的參數值是沒有顯示出來的,這個開發調試過程中很不方便。同樣就算是原生的PreparedStatement同樣如此,那有沒有辦法可以做到列印出來完整的帶參數值的sql呢?答案是有的,利用p6spy,是:sourceforge.net/projects/p6spy/,需要翻牆才可以開啟,下載後解壓,看到一個p6spy.jar和一個spy.properties,分別吧jar加入classpath中,spy.properties放入到你的src目錄下即可,修改properties中的資料來源,比如我的是mysql,我修改成如下:

################################################################## P6Spy Options File                                            ## See documentation for detailed instructions                   #################################################################################################################################### MODULES                                                       ##                                                               ## Modules provide the P6Spy functionality.  If a module, such   ## as module_log is commented out, that functionality will not   ## be available.  If it is not commented out (if it is active),  ## the functionality will be active.                             ##                                                               ## Values set in Modules cannot be reloaded using the            ## reloadproperties variable.  Once they are loaded, they remain ## in memory until the application is restarted.                 ##                                                               ##################################################################module.log=com.p6spy.engine.logging.P6LogFactory#module.outage=com.p6spy.engine.outage.P6OutageFactory################################################################## REALDRIVER(s)                                                 ##                                                               ## In your application server configuration file you replace the ## "real driver" name with com.p6spy.engine.P6SpyDriver. This is ## where you put the name of your real driver P6Spy can find and ## register your real driver to do the database work.            ##                                                               ## If your application uses several drivers specify them in      ## realdriver2, realdriver3.  See the documentation for more     ## details.                                                      ##                                                               ## Values set in REALDRIVER(s) cannot be reloaded using the      ## reloadproperties variable.  Once they are loaded, they remain ## in memory until the application is restarted.                 ##                                                               ################################################################### oracle driver# realdriver=oracle.jdbc.driver.OracleDriver
# mysql Connector/J driver# realdriver=com.mysql.jdbc.Driver# informix driver# realdriver=com.informix.jdbc.IfxDriver# ibm db2 driver# realdriver=COM.ibm.db2.jdbc.net.DB2Driver# the mysql open source driver#---此處我修改---#
realdriver=com.mysql.jdbc.Driver#specifies another driver to use#---此處我修改---#
#realdriver2=#specifies a third driver to use#---此處我修改---#
#realdriver3=#the DriverManager class sequentially tries every driver that is#registered to find the right driver.  In some instances, it's possible to#load up the realdriver before the p6spy driver, in which case your connections#will not get wrapped as the realdriver will "steal" the connection before#p6spy sees it.  Set the following property to "true" to cause p6spy to#explicitily deregister the realdrivers#---此處我修改---#
deregisterdrivers=true################################################################# P6LOG SPECIFIC PROPERTIES                                    ################################################################## no properties currently available################################################################# EXECUTION THRESHOLD PROPERTIES                               ################################################################## This feature applies to the standard logging of P6Spy.       # # While the standard logging logs out every statement          ## regardless of its execution time, this feature puts a time   # # condition on that logging.  Only statements that have taken  # # longer than the time specified (in milliseconds) will be     ## logged.  This way it is possible to see only statements that ## have exceeded some high water mark.                          ## This time is reloadable.                                     ### executionthreshold=integer time (milliseconds)#executionthreshold=################################################################# P6OUTAGE SPECIFIC PROPERTIES                                 ################################################################## Outage Detection## This feature detects long-running statements that may be indicative of# a database outage problem. If this feature is turned on, it will log any# statement that surpasses the configurable time boundary during its execution.# When this feature is enabled, no other statements are logged except the long# running statements. The interval property is the boundary time set in seconds.# For example, if this is set to 2, then any statement requiring at least 2 # seconds will be logged. Note that the same statement will continue to be logged# for as long as it executes. So if the interval is set to 2, and the query takes# 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).## outagedetection=true|false# outagedetectioninterval=integer time (seconds)#outagedetection=falseoutagedetectioninterval=################################################################# COMMON PROPERTIES                                            ################################################################## filter what is loggedfilter=false# comma separated list of tables to include when filteringinclude     = # comma separated list of tables to exclude when filteringexclude     =# sql expression to evaluate if using regex filteringsqlexpression = # turn on tracingautoflush   = true# sets the date format using Java's SimpleDateFormat routinedateformat=#list of categories to explicitly include includecategories=#list of categories to exclude: error, info, batch, debug, statement,#commit, rollback and result are valid valuesexcludecategories=info,debug,result,batch#allows you to use a regex engine or your own matching engine to determine #which statements to log##stringmatcher=com.p6spy.engine.common.GnuRegexMatcher#stringmatcher=com.p6spy.engine.common.JakartaRegexMatcherstringmatcher=# prints a stack trace for every statement loggedstacktrace=false# if stacktrace=true, specifies the stack trace to printstacktraceclass=# determines if property file should be reloadedreloadproperties=false# determines how often should be reloaded in secondsreloadpropertiesinterval=60#if=true then url must be prefixed with p6spy:useprefix=false#specifies the appender to use for logging#appender=com.p6spy.engine.logging.appender.Log4jLoggerappender=com.p6spy.engine.logging.appender.StdoutLogger#appender=com.p6spy.engine.logging.appender.FileLogger# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log) (used for file logger only)logfile     = spy.log# append to  the p6spy log file.  if this is set to false the# log file is truncated every time.  (file logger only)append=true#The following are for log4j logging only#---此處我修改---#
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppenderlog4j.appender.STDOUT.layout=org.apache.log4j.PatternLayoutlog4j.appender.STDOUT.layout.ConversionPattern=p6spy - %m%n#log4j.appender.CHAINSAW_CLIENT=org.apache.log4j.net.SocketAppender#log4j.appender.CHAINSAW_CLIENT.RemoteHost=localhost#log4j.appender.CHAINSAW_CLIENT.Port=4445#log4j.appender.CHAINSAW_CLIENT.LocationInfo=truelog4j.logger.p6spy=INFO,STDOUT################################################################## DataSource replacement                                        ##                                                               ## Replace the real DataSource class in your application server  ## configuration with the name com.p6spy.engine.spy.P6DataSource,## then add the JNDI name and class name of the real ## DataSource here            ##                                                               ## Values set in this item cannot be reloaded using the          ## reloadproperties variable.  Once it is loaded, it remains     ## in memory until the application is restarted.                 ##                                                               ###################################################################realdatasource=/RealMySqlDS#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource################################################################## DataSource properties                                         ##                                                               ## If you are using the DataSource support to intercept calls    # # to a DataSource that requires properties for proper setup,    ## define those properties here. Use name value pairs, separate  ## the name and value with a semicolon, and separate the         ## pairs with commas.                                            ##                         ## The example shown here is for mysql                         ##                                                               ###################################################################realdatasourceproperties=port;3306,serverName;ibmhost,databaseName;mydb################################################################## JNDI DataSource lookup                                        ##                                                               ## If you are using the DataSource support outside of an app     ## server, you will probably need to define the JNDI Context     ## environment.                                                  ##                                                               ## If the P6Spy code will be executing inside an app server then ## do not use these properties, and the DataSource lookup will   ## use the naming context defined by the app server.             ##                                                               ## The two standard elements of the naming environment are## jndicontextfactory and jndicontextproviderurl. If you need    ## additional elements, use the jndicontextcustom property.      ## You can define multiple properties in jndicontextcustom,      ## in name value pairs. Separate the name and value with a       ## semicolon, and separate the pairs with commas.                ##                                                               ## The example shown here is for a standalone program running on ## a machine that is also running JBoss, so the JDNI context     ## is configured for JBoss (3.0.4).                              ##                                                               ###################################################################jndicontextfactory=org.jnp.interfaces.NamingContextFactory#jndicontextproviderurl=localhost:1099#jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.nameing:org.jnp.interfaces#jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory#jndicontextproviderurl=iiop://localhost:900

 

然後把真正用到資料來源的地方修改成:com.p6spy.engine.spy.P6SpyDriver即可。

 

我是用的spring3來做的,所以只需要修改上面幾個地方即可,別的無需在做修改,就可以使用了。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.