Skip to lesson

Seeing the SQL Hibernate generates

Hibernate writes the SQL for you, so a slow page can hide dozens of queries you never typed. In ShopLite you turn the SQL log on while you develop and keep it off on the server.

show-sql vs the org.hibernate.SQL logger

org.hibernate.SQL is the Hibernate logger that prints every generated SQL statement through the normal logging system, so each line has a time, a thread and a level. Switch it on with logging.level.org.hibernate.SQL=DEBUG.

Two settings print Hibernate's SQL. Example 1 uses spring.jpa.show-sql; Example 2 uses the logger and prints the same statements as normal log lines.

Example 1 · src/main/java/com/shoplite/lab/category/SqlLogDemo.java with show-sql=true

Runs in: the jpa-lab Spring Boot project with the ShopLite database

Java
package com.shoplite.lab.category;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
/** Three repository calls, so the SQL log has something to show. */@Componentclass SqlLogDemo implements CommandLineRunner {
    private final CategoryRepository categories;
    SqlLogDemo(CategoryRepository categories) {        this.categories = categories;    }
    @Override    public void run(String... args) {        System.out.println("--- count()");        System.out.println("Categories: " + categories.count());
        System.out.println("--- findById(2)");        categories.findById(2)                .ifPresent(c -> System.out.println("Found: " + c.getName()));
        System.out.println("--- findAll()");        System.out.println("Loaded " + categories.findAll().size() + " categories");    }}
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql --spring.jpa.show-sql=true
    ...
--- count()
Hibernate: select count(*) from categories c1_0
Categories: 7
--- findById(2)
Hibernate: select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Found: Mobiles
--- findAll()
Hibernate: select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0
Loaded 7 categories

What this code does

  • Three repository calls, three statements. count() becomes select count(*), findById(2) a SELECT with where c1_0.category_id=?, findAll() a SELECT with no WHERE.
  • Each Hibernate: line is printed with System.out: no time, no thread, no level, and no way to turn it off per environment except the property itself.
  • The value 2 does not appear anywhere: show-sql never prints bound values. (--lab.demo=sql is a lab-only switch that picks which demo runner runs.)

Example 2 · application.yml: SQL through the logger instead

Runs in: the jpa-lab Spring Boot project with the ShopLite database

YAML
logging:  level:    org.hibernate.SQL: DEBUG     # every statement Hibernate sends
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql --logging.level.org.hibernate.SQL=DEBUG
    ...
--- count()
2026-10-16T11:29:11.745+05:30 DEBUG 19420 --- [jpa-lab] [           main] org.hibernate.SQL                        : select count(*) from categories c1_0
Categories: 7
--- findById(2)
2026-10-16T11:29:11.828+05:30 DEBUG 19420 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Found: Mobiles
--- findAll()
2026-10-16T11:29:11.928+05:30 DEBUG 19420 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0
Loaded 7 categories

What this code does

  • The same three statements, now as normal log lines with a timestamp, the level DEBUG, the thread main and the logger name org.hibernate.SQL.
  • Because it is an ordinary logger, everything from Section 15 applies: levels per profile, log files, JSON format in production.
  • The run passes the setting as a -- command-line argument, which Spring treats exactly like the YAML line; remove spring.jpa.show-sql when you use it, or each statement is printed twice.

show-sql=true prints a bare Hibernate: line with System.out, ignoring your log settings. The logger is the better choice: you can switch it per profile, send it to a file or to structured JSON logs, and see which request thread ran which query. Use one of them, not both, or every statement appears twice.

Logger names changed in Hibernate 7: statements are under org.hibernate.SQL and bound values under org.hibernate.orm.jdbc.bind. Tutorials for Hibernate 5 use org.hibernate.type.descriptor.sql, which no longer prints anything.

Readable SQL and bound values

org.hibernate.orm.jdbc.bind is the Hibernate logger that prints the value sent for each ? in a statement. At level TRACE it prints lines such as binding parameter (1:INTEGER) <- [2].

The SQL log shows ? where a value goes. Example 3 makes the statements readable with format_sql; Example 4 adds the bind logger to see each value.

Example 3 · format_sql: one clause per line

Runs in: the jpa-lab Spring Boot project with the ShopLite database

YAML
spring:  jpa:    properties:      hibernate:        format_sql: true         # passed straight to Hibernatelogging:  level:    org.hibernate.SQL: DEBUG
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql --logging.level.org.hibernate.SQL=DEBUG --spring.jpa.properties.hibernate.format_sql=true
    ...
--- count()
2026-10-16T11:29:27.502+05:30 DEBUG 20112 --- [jpa-lab] [           main] org.hibernate.SQL                        : 
    select
        count(*) 
    from
        categories c1_0
Categories: 7
--- findById(2)
2026-10-16T11:29:27.618+05:30 DEBUG 20112 --- [jpa-lab] [           main] org.hibernate.SQL                        : 
    select
        c1_0.category_id,
        c1_0.name,
        c1_0.parent_id 
    from
        categories c1_0 
    where
        c1_0.category_id=?
Found: Mobiles
--- findAll()
2026-10-16T11:29:27.728+05:30 DEBUG 20112 --- [jpa-lab] [           main] org.hibernate.SQL                        : 
    select
        c1_0.category_id,
        c1_0.name,
        c1_0.parent_id 
    from
        categories c1_0
Loaded 7 categories

What this code does

  • Each statement starts on the line after the log header, with select, from and where on their own lines and one column per line.
  • This is easy to read for joins with many columns; for a quick count of statements the one-line form is more compact. Choose per taste; both show the same SQL.
  • spring.jpa.properties.* is the door to any Hibernate setting that Spring Boot has no property for.

Example 4 · Bound values with org.hibernate.orm.jdbc.bind=TRACE

Runs in: the jpa-lab Spring Boot project with the ShopLite database

YAML
logging:  level:    org.hibernate.SQL: DEBUG    org.hibernate.orm.jdbc.bind: TRACE    # the value sent for each ?
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql --logging.level.org.hibernate.SQL=DEBUG --logging.level.org.hibernate.orm.jdbc.bind=TRACE
    ...
--- count()
2026-10-16T11:29:49.611+05:30 DEBUG 25124 --- [jpa-lab] [           main] org.hibernate.SQL                        : select count(*) from categories c1_0
Categories: 7
--- findById(2)
2026-10-16T11:29:49.691+05:30 DEBUG 25124 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
2026-10-16T11:29:49.692+05:30 TRACE 25124 --- [jpa-lab] [           main] org.hibernate.orm.jdbc.bind              : binding parameter (1:INTEGER) <- [2]
Found: Mobiles
--- findAll()
2026-10-16T11:29:49.791+05:30 DEBUG 25124 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0
Loaded 7 categories

What this code does

  • Right after the findById statement comes binding parameter (1:INTEGER) <- [2]: the first ? received the integer 2.
  • count() and findAll() have no parameters, so no bind lines follow them.
  • The level must be TRACE; at DEBUG the bind logger prints nothing.

spring.jpa.properties.hibernate.format_sql=true prints each statement over several lines, one clause per line; anything under spring.jpa.properties is passed straight to Hibernate. The ? marks a parameter of a prepared statement, which protects against SQL injection. In binding parameter (1:INTEGER) <- [2], the 1 is the parameter number, INTEGER the JDBC type and 2 the value.

Bound values can be customer data, such as e-mail addresses, phone numbers or names. That is fine on your own computer with seed data; it is one more reason to keep this logging out of production.

Predict the output

Read the bind log

Pick what the log shows.

Round 1 of 2

The log shows this statement, then the line below it. Which category was loaded?

select c1_0.category_id,c1_0.name,c1_0.parent_id
from categories c1_0
where c1_0.category_id=?
binding parameter (1:INTEGER) <- [2]

Reading a generated SELECT

A table alias is a short name given to a table inside one SQL statement, like c1_0 in from categories c1_0. Hibernate builds it from the entity name (c), the first use (1) and an internal counter (_0).

A generated query looks unusual, but it follows a fixed pattern. The snippet reads one generated SELECT line by line.

SQL
select    c1_0.category_id,     -- @Id field id, @Column(name = "category_id")    c1_0.name,            -- field name    c1_0.parent_id        -- field parentId (Spring Boot's naming rule)from    categories c1_0       -- @Table(name = "categories"), alias c1_0where    c1_0.category_id=?    -- findById(2): the 2 is bound to this ?

The column list is every mapped column, in the entity's field order, never SELECT *, because Hibernate needs them all to build complete objects. If a column you expect is missing, the field is not mapped; if a column you do not know appears, check the entity. With joins you will see c1_0, p1_0 and so on.

The WHERE clause uses ? for parameters, and the bind log line right after it gives the value. Read them together: the query and binding parameter (1:INTEGER) <- [2] mean "load category 2".

Counting statements with hibernate.generate_statistics

Session metrics are Hibernate's summary of one session: JDBC connections, prepared and executed statements, batches, cache use and flushes, each with its time. They need hibernate.generate_statistics=true and the org.hibernate.session.metrics logger at DEBUG.

Example 5 counts what Hibernate does in one repository call. Both settings must be on, or no summary appears.

Example 5 · generate_statistics: a summary per session

Runs in: the jpa-lab Spring Boot project with the ShopLite database

YAML
spring:  jpa:    properties:      hibernate:        generate_statistics: truelogging:  level:    org.hibernate.SQL: DEBUG    org.hibernate.session.metrics: DEBUG   # Hibernate 7 logs the summary here
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql --spring.jpa.properties.hibernate.generate_statistics=true --logging.level.org.hibernate.session.metrics=DEBUG --logging.level.org.hibernate.SQL=DEBUG
    ...
--- count()
2026-10-16T11:34:06.714+05:30 DEBUG 1092 --- [jpa-lab] [           main] org.hibernate.SQL                        : select count(*) from categories c1_0
2026-10-16T11:34:06.758+05:30 DEBUG 1092 --- [jpa-lab] [           main] org.hibernate.session.metrics            : HHH000401: Logging session metrics:
	1466700 ns acquiring 1 JDBC connections
	0 ns releasing 0 JDBC connections
	6036000 ns preparing 1 JDBC statements
	3882600 ns executing 1 JDBC statements
	0 ns executing 0 JDBC batches
	0 ns performing 0 second-level cache puts
	0 ns performing 0 second-level cache hits
	0 ns performing 0 second-level cache misses
	0 ns executing 0 flushes (flushing a total of 0 entities and 0 collections)
	385600 ns executing 1 pre-partial-flushes
	405100 ns executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)

Categories: 7
    ...

What this code does

  • After count(), Hibernate logs HHH000401: Logging session metrics: 1 connection acquired, 1 statement prepared, 1 executed, each with its time in nanoseconds.
  • There is one summary per repository call here, because each call runs in its own short session. Inside one @Transactional service method the summary would cover all its statements.
  • With generate_statistics on but the metrics logger at its default level, the run prints no summary at all; both settings are needed.

A session is the unit of work behind one transaction or one repository call. "Executing 1 JDBC statements" per call is what you want; a number that grows with the data, like the 1 + N queries of the mismatch lesson, is a warning sign.

Statistics cost a little time on every query, so use them to investigate, not as a permanent setting. The Performance traps module uses statement counts in tests to keep N+1 queries from coming back.

SQL logging in the dev profile only

Example 6 puts the SQL settings in application-dev.yml, so only the dev profile prints them.

Example 6 · src/main/resources/application-dev.yml: SQL only in dev

Runs in: the jpa-lab Spring Boot project with the ShopLite database

YAML
spring:  jpa:    properties:      hibernate:        format_sql: truelogging:  level:    org.hibernate.SQL: DEBUG    org.hibernate.orm.jdbc.bind: TRACE
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql
    ...
2026-10-16T11:30:44.916+05:30  INFO 3768 --- [jpa-lab] [           main] com.shoplite.lab.JpaLabApplication       : No active profile set, falling back to 1 default profile: "default"
    ...
--- count()
Categories: 7
--- findById(2)
Found: Mobiles
--- findAll()
Loaded 7 categories

$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=sql --spring.profiles.active=dev
    ...
2026-10-16T11:30:21.572+05:30  INFO 22908 --- [jpa-lab] [           main] com.shoplite.lab.JpaLabApplication       : The following 1 profile is active: "dev"
    ...
--- count()
2026-10-16T11:30:39.194+05:30 DEBUG 22908 --- [jpa-lab] [           main] org.hibernate.SQL                        : 
    select
        count(*) 
    from
        categories c1_0
Categories: 7
--- findById(2)
2026-10-16T11:30:39.306+05:30 DEBUG 22908 --- [jpa-lab] [           main] org.hibernate.SQL                        : 
    select
        c1_0.category_id,
        c1_0.name,
        c1_0.parent_id 
    from
        categories c1_0 
    where
        c1_0.category_id=?
2026-10-16T11:30:39.309+05:30 TRACE 22908 --- [jpa-lab] [           main] org.hibernate.orm.jdbc.bind              : binding parameter (1:INTEGER) <- [2]
Found: Mobiles
    ...

What this code does

  • Without a profile the lab runs as default: the three calls work and no SQL is printed, because the base application.yml has no SQL settings.
  • With --spring.profiles.active=dev, Spring also reads application-dev.yml: formatted SQL plus the bound value appear.
  • ShopLite sets spring.profiles.default: dev, so developers get this without the flag, and the server runs with prod, where the file is never read.

In production, SQL logging slows the app and fills the disk: a busy shop sends thousands of statements a minute. Bind logging is worse there, because it writes customers' e-mails and phone numbers into log files. In the dev profile file, the settings apply only on your own computer, and the base application.yml and application-prod.yml stay quiet.

ShopLite already makes dev the default profile (spring.profiles.default: dev) and starts the server with prod. So a developer sees SQL without doing anything, and the server never does.

Find the bug

Find the logging mistake

Pick the line that causes the problem.

Every SQL statement appears twice in the console. Which line is the cause?

Round 1 of 2

Next step

Check your understanding

12 quick questions