当前位置:Gxlcms > 数据库问题 > 打印hibernate的SQL语句的几种办法

打印hibernate的SQL语句的几种办法

时间:2021-07-01 10:21:17 帮助过:118人阅读

绝对不要把这些配置提交到上线代码中!


首先,我们需要引入相关jar包。

pom.xml

<!-- https://mvnrepository.com/artifact/p6spy/p6spy -->

<dependency>

    <groupId>p6spy</groupId>

    <artifactId>p6spy</artifactId>

    <version>3.0.0</version>

</dependency>

第二,我们需要“处理”一下数据源配置。

spring-db.xml

<bean id="dataSource" class="com.p6spy.engine.spy.P6DataSource">

    <constructor-arg>

        <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"

            destroy-method="close">

            <property name="driverClass" value="org.h2.Driver" />

            <property name="jdbcUrl"

                value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;IGNORECASE=TRUE;MODE=MySQL;MVCC=true" />

            <property name="user" value="sa" />

            <property name="password" value="" />

        </bean>

    </constructor-arg>

</bean>

最后,我们需要为p6spy增加一个配置文件,放到resource路径下。其中可配置项很多,我们可以只配置一部分(例如示例中的三项)。完整配置可以查看他们的官网。

p6spy.properties

# 默认会在项目路径下创建spy.log

logfile = C:/Users/Administrator/Desktop/log/spy.log

# 默认apptend=true,会导致日志文件不断扩大

append=false

# 默认是dd-MMM-yy

databaseDialectDateFormat=yyyy-MM-dd

 

配置好之后,spy.log中应该会有这样的输出。红色字体部分就是带有参数的SQL语句。

1485070310889|0|statement|connection 10|select companyacc0_.id as id1_24_, companyacc0_.balance as balance2_24_, companyacc0_.lastUpdateTime as lastUpda3_24_, companyacc0_.type as type4_24_ from company_accounts companyacc0_ where companyacc0_.type=?|select companyacc0_.id as id1_24_, companyacc0_.balance as balance2_24_, companyacc0_.lastUpdateTime as lastUpda3_24_, companyacc0_.type as type4_24_ from company_accounts companyacc0_ where companyacc0_.type=‘MAIN‘

 


 

参考

使用hibernate的show_sql方式配置:http://www.mkyong.com/hibernate/hibernate-display-generated-sql-to-console-show_sql-format_sql-and-use_sql_comments/

使用Log4j配置:http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-log4j/

使用P6spy配置:http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-solution/

P6spy官方配置说明:http://p6spy.readthedocs.io/en/latest/configandusage.html


本文出自 “编程的摩羯男” 博客,请务必保留此出处http://winters1224.blog.51cto.com/3021203/1894055

打印hibernate的SQL语句的几种办法

标签:hibernate;sql;参数;打印;

人气教程排行