I am learning about the wonders of JdbcTemplate and NamedParameterJdbcTemplate. I like what I see, but is there any easy way to see the underlying SQL that it ends up executing? I'd like to see this for debug purposes (in order to for example debug the resulting SQL in an outside tool).
The Spring documentation says they're logged at DEBUG level:
All SQL issued by this class is logged at the DEBUG level under the category corresponding to the fully qualified class name of the template instance (typically JdbcTemplate, but it may be different if you are using a custom subclass of the JdbcTemplate class).
In XML terms, you need to configure the logger something like:
<category name="org.springframework.jdbc.core.JdbcTemplate">
<priority value="debug" />
</category>
This subject was however discussed here a month ago and it seems not as easy to get to work as in Hibernate and/or it didn't return the expected information: Spring JDBC is not logging SQL with log4j This topic under each suggests to use P6Spy which can also be integrated in Spring according this article.
This works for me with org.springframework.jdbc-3.0.6.RELEASE.jar. I could not find this anywhere in the Spring docs (maybe I'm just lazy) but I found (trial and error) that the TRACE level did the magic.
I'm using log4j-1.2.15 along with slf4j (1.6.4) and properties file to configure the log4j:
log4j.logger.org.springframework.jdbc.core = TRACE
This displays both the SQL statement and bound parameters like this:
Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown
Not sure about the SQL type unknown but I guess we can ignore it here
For just an SQL (i.e. if you're not interested in bound parameter values) DEBUG
should be enough.
I use this line for Spring Boot applications:
logging.level.org.springframework.jdbc.core = TRACE
This approach pretty universal and I usually use it for any other classes inside my application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With