如何让@Sql脚本执行的SQL语句显示在控制台日志中?
问题:如何查看@Sql执行的SQL语句日志?
最小可复现示例(MRE)
Java测试类
package com.example.h2_demo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.jdbc.Sql; @DataJpaTest @Sql( executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"/create_user_table.sql", "/insert_user.sql"} ) public class H2DemoApplicationTest { @Test void testNothing() { } @Test void testNothingOneMoreTime() { } }
SQL脚本
create_user_table.sql
-- create_user_table.sql CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY, name VARCHAR(50) NOT NULL, last_name VARCHAR(50) );
insert_user.sql
-- insert_user.sql INSERT INTO users VALUES (1, 'John', 'Doe');
问题详情
已确认@Sql脚本执行成功,但日志中无法看到CREATE或INSERT语句。已配置如下属性(且已存在于target下的application.properties中):
spring.jpa.properties.hibernate.show_sql=true spring.jpa.properties.hibernate.use_sql_comments=true spring.jpa.properties.hibernate.format_sql=true logging.level.org.hibernate.type=trace logging.level.org.springframework.jdbc.core=TRACE logging.level.org.springframework.test.context.jdbc=debug
搜索"insert"无匹配结果,需解决如何在日志中查看@Sql执行的查询语句。
解决方案
@Sql执行的脚本由Spring的JdbcTemplate直接处理,Hibernate的日志配置不会覆盖这部分输出,需调整以下日志级别:
- 添加
logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG:该配置会打印JdbcTemplate执行的SQL语句 - 若需查看SQL参数的具体值,添加
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE
额外注意:
- 现有配置中的
logging.level.org.springframework.jdbc.core=TRACE理论上包含JdbcTemplate的DEBUG级别,但单独指定JdbcTemplate的级别可避免日志框架优先级导致的生效问题 - 若使用Logback等日志框架,需确保框架配置文件未覆盖上述级别设置
内容的提问来源于stack exchange,提问作者Sergey Zolotarev
相关产品推荐
相关产品推荐

