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

To log sql in Hibernate

Jerry You
Greenhorn

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"/>
</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

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
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 16622

or check out p6spy.com

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Jerry You
Greenhorn

Joined: Dec 09, 2005
Posts: 6
Indeed - even better.
 
 
subject: To log sql in Hibernate
 
Threads others viewed
Logging Package Specific logs using LOG4J
Child record not saved in one-to-many hibernate
log4j - creating my own file
Aspectj & Log4j problem
Logging into database
MyEclipse, The Clear Choice

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture