让Hibernate展示SQL语句的绑定参数值

让Hibernate显示SQL语句的绑定参数值

使用Hibernate提供的内置属性<Property name="show_sql">true</Property>只能输出类似于下面的SQL

Hibernate: insert into aticle (content, aticle_id) values (?, ?)

这样不利于程序的调试,为了可以显示?占位符所代表的具体数据,需要第三方Jar包,p6spy是一个该需求的开源实现。

一、在Java Project项目中使用p6spy:

  1. 到http://sourceforge.net/projects/p6spy/下载其Jar包。
  2. 将其解压缩,将里面的p6spy.jar放入构建路径里,将spy.properties文件放入src目录下。
  3. 修改两个属性,第一个,realdriver=你使用具体数据库的驱动类(例如Oralce为:realdriver=oracle.jdbc.driver.OracleDriver);第二个,logfile=指定log文件的位置(例如logfile= E:/tmp/spy.log)。
  4. 修改Hibernate.cfg.xml配置文件中的 <property name="hibernate.connection.driver_class">com.p6spy.engine.spy.P6SpyDriver</property>

配置完毕后,执行HQL语句后,查看spy.log文件就可以看到?占位符的具体数据了:(前面部分是Hibernate的初始化信息,最下面显示的就是完整的SQL语句)

1363760581228|1|0|commit||
1363760581471|135|0|statement||select sequence_name from user_sequences
1363760581490|-1||resultset|select sequence_name from user_sequences|SEQUENCE_NAME = HIBERNATE_SEQUENCE
1363760588977|3|0|statement|select hibernate_sequence.nextval from dual|select hibernate_sequence.nextval from dual
1363760589081|75|0|statement|insert into aticle (content, aticle_id) values (?, ?)|insert into aticle (content, aticle_id) values ('内容', 55241)
1363760589083|1|0|commit||

二、在Java Web项目中使用p6spy(Tomcat环境下)

  1. 将p6spy.jar 放入应用程序的WEB-INF/lib目录,将spy.properties放入WEB-INF/classes目录
  2. 其他与Java Project项目使用方法一样。
  3. 重启Tomcat服务器

可能会出现的问题:驱动程序加载先后的问题解决

如果spy.log里出现你的程序的数据库驱动名称 is a real driver in spy.properties, but it has been loaded before p6spy. p6spy will not wrap these connections. Either prevent the driver from loading, or try setting 'deregisterdrivers' to true in spy.properties.

请把spy.properties文件里的deregisterdrivers=false改为deregisterdrivers=true,重新运行即可。

 

转自:http://www.cnblogs.com/otomedaybreak/archive/2012/01/17/show_full_sql_by_p6spy_in_hibernate.html