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?
In Java:
Transform your query in TypedQuery if it's a CriteriaQuery (javax.persistence).
Then:
query.unwrap(org.hibernate.Query.class).getQueryString();
If you are using spring boot and jpa
tells hibernate to hide logs
true seems to be default!!
Change
hibernate.cfg.xml
to:Include log4j and below entries in "log4j.properties":
turn on the
org.hibernate.type
Logger to see how the actual parameters are bind to the question marks.You can do it using the datasource-proxy, as I described in this post.
Assuming your application expects a
dataSource
bean (e.g. via@Resource
), this is how you can configuredatasource-proxy
:Now the Hibernate output vs datasource-proxy:
The
datasource-proxy
queries contain parameter values and you can even add custom JDBC statement interceptors so that you can catch N+1 query issues right from your integration tests.Log4JDBC is a nice solution which prints the exact SQL going to the database with parameters in place rather than the most popular answer here which does not do this. One major convenience of this is that you can copy the SQL straight to your DB front-end and execute as is.
http://log4jdbc.sourceforge.net/
https://code.google.com/p/log4jdbc-remix/
The latter also outputs a tabular representation of query results.
Sample Output showing generated SQL with params in place together with result set table from query:
Update 2016
Most recently I have now been using log4jdbc-log4j2 (https://code.google.com/archive/p/log4jdbc-log4j2/ ) with SLF4j and logback. Maven dependencies required for my set-up are as below:
The Driver and DB Urls then look like:
My logback.xml configuration file looks like the below: this outputs all SQL statements with parameters plus the resultset tables for all queries.
Finally, I had to create a file named log4jdbc.log4j2.properties at the root of the classpath e.g. src/test/resources or src/main/resources in a Mevn project. This file has one line which is the below:
The above will depend on your logging library. See the docs at https://code.google.com/archive/p/log4jdbc-log4j2 for further info
Sample Output: