在 Hibernate 中,如果想打印出它生成的 SQL 语句(包括执行的 SQL 查询),可以通过以下几种方式来实现:
方式一:修改配置文件
在 hibernate.cfg.xml
或 application.properties
/ application.yml
中开启 SQL 日志。
XML 配置(hibernate.cfg.xml)
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
Spring Boot – application.properties
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
方式二:使用日志框架打印完整 SQL(含参数)
如果你想查看 带参数的完整 SQL(推荐),需要开启 Hibernate 的 SQL 日志:
application.properties
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE
说明:
org.hibernate.SQL=DEBUG
:打印 SQL 模板语句。org.hibernate.type.descriptor.sql=TRACE
:打印参数绑定信息。
方式三:使用 Hibernate 拦截器 / 监听器
可以通过实现 Hibernate 拦截器自定义打印逻辑,但一般来说前两种方式已经足够开发使用。
效果示例(开启 SQL 日志后):
Hibernate:
select
user0_.id as id1_0_,
user0_.name as name2_0_
from
user user0_
where
user0_.id=?
binding parameter [1] as [INTEGER] - [1]