看到 Spring JdbcTemplate 中的底层 SQL 了吗?
我正在了解 JdbcTemplate 和 NamedParameterJdbcTemplate 的奇妙之处。我喜欢我所看到的,但是有没有简单的方法来查看它最终执行的底层 SQL?我希望看到这一点用于调试目的(例如,为了在外部工具中调试生成的 SQL)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
Spring 文档 表示它们已记录在调试级别:
在 XML 术语中,您需要配置记录器,如下所示:
然而,一个月前已经在这里讨论了这个主题,看起来似乎不像 Hibernate 那样容易开始工作和/或它没有返回预期的信息: Spring JDBC 不使用 log4j 记录 SQL。您还可以使用 P6Spy 代替,也可以是 集成在 Spring Boot 中。
The Spring documentation says they're logged at DEBUG level:
In XML terms, you need to configure the logger something like:
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. You could also use P6Spy instead which can also be integrated in Spring Boot.
这对我来说适用于 org.springframework.jdbc-3.0.6.RELEASE.jar。
我在 Spring 文档中找不到这个(也许我只是懒),但我发现(反复试验)TRACE 级别发挥了魔力。
我正在使用 log4j-1.2.15 以及 slf4j (1.6.4) 和属性文件来配置 log4j:
这会显示 SQL 语句和绑定参数,如下所示:
不确定 SQL 类型未知,但我想我们可以忽略它在这里
对于只是一个 SQL(即,如果您对绑定参数值不感兴趣)
DEBUG
应该足够了。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:
This displays both the SQL statement and bound parameters like this:
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.我将这一行用于 Spring Boot 应用程序:
这种方法非常通用,我通常将其用于应用程序中的任何其他类。
I use this line for Spring Boot applications:
This approach pretty universal and I usually use it for any other classes inside my application.
参数值似乎是在 TRACE 级别上打印的。这对我有用:
控制台输出:
Parameter values seem to be printed on TRACE level. This worked for me:
Console output:
这对我来说适用于 log4j2 和 xml 参数:
结果控制台和文件日志是:
只需复制/过去
HTH
This worked for me with log4j2 and xml parameters:
Result console and file log was:
Just copy/past
HTH
尝试在 log4j.xml 中添加
您的日志,如下所示:
Try adding in log4j.xml
your logs looks like:
不需要任何 xml 或 yml 配置就可以做到这一点,但就像纯 java 代码一样简单,如下所示:
享受它,伙计们,
从这里查看更多信息 https://www.bswen.com/2019/05/springboot-How-to-print-JPA-and-jdbcTemplate-SQL-logs.html
One can do this without any xml or yml config , but as simple as only pure java code ,like below:
Enjoy it, guys,
see more from here https://www.bswen.com/2019/05/springboot-How-to-print-JPA-and-jdbcTemplate-SQL-logs.html
如果您使用 ch.qos.logback 添加记录器:
In case you use ch.qos.logback add a logger: