Video in progress

Strong Junior 🌱 Spring

How do you see the SQL queries Hibernate sends, with their parameters, and why is show-sql not enough?

spring.jpa.show-sql prints SQL without parameters straight to System.out. The right way is through a logger: org.hibernate.SQL=DEBUG shows the query, and in Hibernate 6 org.hibernate.orm.jdbc.bind=TRACE shows the parameter values.

📖 Answer

What you get with show-sql=true:

Hibernate: select o1_0.id,o1_0.status from orders o1_0 where o1_0.customer_id=?

The problems: you can't tell what's in place of ?, it doesn't go through the logging system (no timestamp, thread or trace id), and turning it off needs a redeploy.

With loggers:

logging:
  level:
    org.hibernate.SQL: debug
    org.hibernate.orm.jdbc.bind: trace     # Hibernate 6
spring:
  jpa:
    properties:
      hibernate.format_sql: true

In Hibernate 5 the category for parameters was different: org.hibernate.type.descriptor.sql. That's why the old setting stops working when you move to Boot 3.

Two more useful things:

  • hibernate.generate_statistics=true shows how many queries ran in each session and helps you find N+1 quickly;
  • datasource-proxy or p6spy print ready SQL with the parameters filled in, plus the execution time.

Be careful in prod: bind=trace writes user data and passwords to the log and sharply increases log volume. If you need it, turn it on temporarily through Actuator's /loggers endpoint and then turn it back off.