是否有可能获得导致 Spring DataAccessException 的 SQL 查询?

Is it possible to get the SQL query causing a Spring DataAccessException?

我有一个应用程序使用 JdbcTemplate 在 MySQL 数据库上执行查询。如果 JdbcTemplate 曾抛出 org.springframework.dao.DataAccessException,它会记录异常的堆栈跟踪。但是,我还想包含导致抛出异常的 SQL 查询。有没有一种简单的方法可以做到这一点,而不涉及为每个使用 JdbcTemplate 的地方编写自定义错误消息?

如果您只打算在异常期间记录 SQL 语句,您可能必须编写自己的 JdbcTemplate 的自定义子类并更改记录先决条件,如源代码中所示 Github.

如果不是这样,您可以考虑以下。

Spring documentation 开始,所有 SQL 语句都记录在 DEBUG 级别。

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).

您还通过将 profileSQL 设置为 true 来更改 Jdbc url 以跟踪 SQL。

MySQl Connection Reference Documentation