How to print a query string with parameter values when using Hibernate
Turn on Hibernate SQL and parameter logging via your logging system. For org.hibernate.SQL
, set log level to DEBUG
and for org.hibernate.type.descriptor.sql.BasicBinder
, set it to TRACE
. This will track SQL statements and bind parameter values:
For Logback users:
Do remember to set format_sql
to true in Hibernate configuration for readable logs.
Enhancing existing logging abilities
While Hibernate does offer a basic SQL output through hibernate.show_sql
, getting a hang of the actual parameters can be a bit tricky.
Unlocking the secrets of built-in capabilities
Modify your logging configurations to to optimize Hibernate's hibernate.show_sql
functionality:
This ensures Hibernate's Formatted output doesn't clash with that of your logging framework.
P6Spy: The JDBC 007
When Hibernate simply doesn't cut it, turn to solutions like P6Spy. Acting as a wrapper around your JDBC driver, P6Spy logs SQL alongside actual parameters for complete operational transparency.
You'll need to "spyify" your JDBC URL to rout connections via P6Spy:
Upgrading your Hibernate game
The newer versions of Hibernate, Hibernate 6 in particular, make parameter value logging a breeze by simplifying configurations:
Advanced configurations for better insights
Becoming a master chef in Hibernate logging involves understanding the layers of your tech stack and how they interact. Here are a few tips to spice up your log output.
Refining your logging recipe
Your log4j.xml
or logback.xml
is not just for recording. You get to define file locations, rolling policies, and formats - just like preparing a perfect dish. Always set the additivity property to false to avoid spillovers.
Mind the Logal Food Inspector!
Just like you wouldn't serve a dish you haven't tasted, each log file should be inspected for sensitive data. Audit your logs, judiciously use logging levels, consider filtering or obfuscating sensitive data. But beware, overcooking the logs can cost you performance!
Consulting the official cookbook: Hibernate guide
The Hibernate user guide covers session configurations and logging options. You can customize configurations in hibernate.cfg.xml
even if you're not using Spring. The guide's always a handy reference to keep around for checking recipe revisions.
Integrating with the Java kitchen
Various Java frameworks like Spring Boot 3, simplify property maintenance with application.yml
or .properties
files. This eases the integration process and adds flexibility to your code.
Was this article helpful?