Is it possible in Hibernate to print generated SQL queries with real values instead of question marks?
How would you suggest to print queries with real values if it is not possible with Hibernate API?
Is it possible in Hibernate to print generated SQL queries with real values instead of question marks?
How would you suggest to print queries with real values if it is not possible with Hibernate API?
Use Wireshark or something similar:
None of the above mentioned answers will print SQL with parameters properly, or it is a pain to get it working with them. I achieved this by using WireShark, which captures all SQL/commands being send from the application to Oracle/MySQL etc. with the queries.
The simplest solution for me is implementing a regular string replacement to replace parameter inputs with parameter values (treating all parameters as string, for simplicity):
String debuggedSql = sql;
// then, for each named parameter
debuggedSql = debuggedSql.replaceAll(":"+key, "'"+value.toString()+"'");
// and finally
System.out.println(debuggedSql);
Or something similar for positional parameters (?).
Take care of null values and specific value types like date, if you want a run ready SQL to be logged.
If you are using spring-boot you can use log4jdbc-spring-boot-starter dependency, which is a fork of org.bgee.log4jdbc-log4j2 .
In pom.xml I used the following dependency:
<dependency>
<groupId>com.integralblue</groupId>
<artifactId>log4jdbc-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
In documentation it's mentioned that if you just include this dependency SQL logging will not work, we have to specify following property in application.properties
logging.level.jdbc.sqlonly=INFO
but with
2.0.0 version, All the logging properties are set to info by default . at time of writing this answer the usage count for 2.0.0 is less compared to 1.0.2
So with 2.0.0 even if you don't specify any properties for logging sql following properties are set by default
logging.level.jdbc.sqlonly=INFO
logging.level.jdbc.resultset=INFO
logging.level.jdbc.connection=INFO
logging.level.jdbc.resultsettable=INFO
logging.level.jdbc.audit=INFO
logging.level.jdbc.sqltiming=INFO
So if you want only SQL queries printed with ? replaced with actual values and avoid unnecessary log from result set these properties explicitly to
logging.level.jdbc.sqlonly=INFO
logging.level.jdbc.resultset=OFF
logging.level.jdbc.connection=OFF
logging.level.jdbc.resultsettable=OFF
logging.level.jdbc.audit=OFF
logging.level.jdbc.sqltiming=OFF
if you don't want to use Loggers, only insert this into application.properties
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true