Logging SQL

show-sql vs Logger Configuration

spring.jpa.show-sql=true prints SQL straight to standard output (fine for learning). The better way is to use the logging system, which also lets you see the parameter values:

application.yml

application.yml

logging:
  level:
    org.hibernate.SQL: DEBUG               # the SQL statements
    org.hibernate.orm.jdbc.bind: TRACE     # parameter values (Hibernate 6)
spring:
  jpa:
    properties:
      hibernate:
        format_sql: true                   # pretty-print
        highlight_sql: true                # colours in the console

Example output

DEBUG org.hibernate.SQL :
    select
        p1_0.id,
        p1_0.category,
        p1_0.description,
        p1_0.name,
        p1_0.price,
        p1_0.stock
    from
        products p1_0
    where
        p1_0.id=?
TRACE org.hibernate.orm.jdbc.bind : binding parameter (1:BIGINT) <- [42]

Note: In Hibernate 5 the bind logger was org.hibernate.type.descriptor.sql.BasicBinder. Hibernate 6 renamed it to org.hibernate.orm.jdbc.bind. Old Stack Overflow answers use the old name.

Reading Hibernate 6 SQL

  • Table aliases look like p1_0 (entity initial + numbers). This is normal.
  • Every mapped column is listed explicitly; Hibernate never uses select *.
  • ? marks bound parameters — proof that the query is safe from SQL injection.
  • Counting the lines starting with Hibernate: per request is the easiest way to spot too many queries (the N+1 problem, medium level).

Tip: Turn SQL logging on in the dev profile and off in prod: logging every query in production is slow and may leak data into logs.