Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

To log sql in Hibernate

 
Jerry You
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are 2 options in current Hibernate regarding loggin sql:
1, show-sql=true this will output the generated sql to system console (if you look at the source, System.out.println() is used)
2, or in the log4j configuration, set "org.hibernate.sql" logging level DEBUG, this way, Hibernate will log to log file, however it will log lots of hibernate activity along with the sql.

Sometime I need to log those generated sql to file, and I want the logged sql to be "real"(or at least close) with real parameters instead of "?" of prepared statement.

What I did was to download the Hibernate source, unzip, add a new wrapper class "LoggablePreparedStatement", which implements the PreparedStatement and also have function to "record" the parameters, I then modified one Hibernate class "AbstractBatcher" to use the new loggablePreparedStatement instead of the regular PreparedStatement.

After this, re-build Hibernate and put it in the classpath. In the log4j, add
<logger name="org.hibernate.jdbc.LoggablePreparedStatement">
<level value="debug"/>
<appender-ref ref="sqlFile"/>
</logger>

This way, I can have better looking sql logged to file and this helps me in debugging.

I hope this will help those who might have same needs (I wish Hibernate development team could do something to improve the sql logging)

Notes: I got the LoggablePreparedStatement several years ago from an IBM article, which I cound not find now.
 
Jerry You
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know how to attach file here. Maybe will post the code (it is very long) later.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or check out p6spy.com

Mark
 
Jerry You
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed - even better.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic