The moose likes Object Relational Mapping and the fly likes To log sql in Hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "To log sql in Hibernate" Watch "To log sql in Hibernate" New topic

To log sql in Hibernate

Jerry You

Joined: Dec 09, 2005
Posts: 6
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"/>

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

Joined: Dec 09, 2005
Posts: 6
I don't know how to attach file here. Maybe will post the code (it is very long) later.
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

or check out


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Jerry You

Joined: Dec 09, 2005
Posts: 6
Indeed - even better.
I agree. Here's the link:
subject: To log sql in Hibernate
jQuery in Action, 3rd edition