Debug Hibernate SQL Behavior With Logging and Statistics
See what Hibernate really sends to the database: SQL logging with bind values, statistics, slow query logs, flush timing and detecting N plus 1 problems.

When a Hibernate-backed feature misbehaves, the cause is almost always visible in the SQL that was or was not sent. A query that returns the wrong rows, a value that is not saved, an update nobody asked for, a request that issues a hundred statements: each leaves a trace. This post is a debugging workflow for those cases rather than a catalogue of settings. It covers how to see the statements, how to get the exact ones, how to count them, and how to explain two of the most confusing behaviours, unexpected updates and unexpected flushes. The basic logging switches are covered in logging SQL and counting statements, and this post assumes you have them on.
Log the SQL
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.orm.jdbc.bind=TRACE
spring.jpa.properties.hibernate.format_sql=trueReproduce the problem with a single request or a single test, and read the log from the top. The first question is whether the statement you expected was sent at all. If a save appears to do nothing, look for the insert or update. Its absence points at a transaction that never committed, a method that never ran because of a proxy problem, or a flush that did not happen. The reasons a transaction does not apply are collected in transactions that do not apply.
Exact statements with a proxy
The Hibernate log shows a statement with ? placeholders and the bound values on separate lines. When you need the statement as the database received it, with values in place, put a proxy around the data source:
@Bean
DataSource dataSource(DataSourceProperties properties) {
DataSource real = properties.initializeDataSourceBuilder().build();
return ProxyDataSourceBuilder.create(real)
.name("app")
.logQueryBySlf4j(SLF4JLogLevel.INFO)
.countQuery()
.build();
}This uses the datasource-proxy library. It logs every statement that crosses the JDBC boundary, including those from code that bypasses Hibernate, which matters if some of your queries use JdbcTemplate or a native call. It also counts statements per type, so a test can ask how many selects ran. Use it in development and tests, since it adds overhead and volume.
Statistics
Hibernate's own counters, enabled with hibernate.generate_statistics, give totals for statements, entity loads and flushes, and a test can assert on them so that a regression fails the build. The usage and the habit of asserting a statement count are in detecting N+1 queries in tests. A slow query threshold with hibernate.log_slow_query=25 logs the statements that exceed it, which narrows a performance investigation without reading the full log.
Spot N plus 1
A query that loads a list, followed by the same single-row select repeated with different ids, is the pattern. In a log it looks like a staircase of near-identical lines. Count the repeats and compare with the number of rows in the first result: they match. The cause is a lazy association touched in a loop, and the fixes are a join fetch, an entity graph or batch fetching, set out in fixing N+1. Confirm the fix by running the same request again and checking that the staircase is gone and the count is constant.
Unexpected updates
You load an entity, only read it, and an update statement appears at commit. Hibernate tracks managed entities and compares their current state with a snapshot taken at load. Any difference, however small, produces an update. The usual causes are a setter or a method that changes a field as a side effect of a read, such as normalising a string in a getter that writes back, a mutable value type such as a Date or a collection replaced with an equal copy, and a BigDecimal whose scale differs from the database's. Find the modified field by reading the update statement's set clause: it lists the columns Hibernate believes changed, which names the culprit. If the changes are not intended, mark the transaction readOnly = true, which turns off the dirty check for the session, and the update disappears.
Unexpected flushes
Hibernate delays writes and sends them at a flush. By default it flushes before running a query whose result could depend on the pending changes, which is called auto flush. So a select in the middle of a method can trigger an insert that you expected to happen at commit, and the log shows the write appear before the read. That is correct behaviour and surprising to read. It also explains a constraint violation that appears at an odd line: the failing statement runs at the flush, not at the line where you called save. If you need to find which line triggered it, set a breakpoint on flush or log with a stack trace for the exception. Calling entityManager.flush() yourself brings the failure forward to a known place, which helps in debugging and in code that wants to report a constraint violation inside the method.
Check the transaction boundaries
Many puzzles are transaction puzzles. Turn on the transaction logs to see where each one begins and ends:
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.orm.jpa=DEBUGThe lines Getting transaction for [...] and Completing transaction for [...] show the method that opened the transaction and when it committed or rolled back. If a write is not visible to another request, check that the commit happened and when. If a lazy load fails with LazyInitializationException, there was no session open at that point; the fix and the causes are in that exception, and the general behaviour of persistence is covered in the Hibernate and JPA guide. Another error that shows up as a SQL problem is saving an entity that refers to an unsaved one, explained in [TransientPropertyValueException](/library/transientpropertyvalueexception-fix-save-spring-data). Check also whether open-in-view is on with spring.jpa.open-in-view, because it keeps the session open through the view and hides lazy loads that then run during rendering.
Order of work when debugging
- Reproduce with the smallest input and a single thread.
- Turn on SQL and bind logging, and read the statements in order.
- Decide whether the missing, extra or wrong statement is the problem.
- Check the transaction logs to see boundaries and rollbacks.
- Count statements before and after your fix.
- Keep a test that asserts the count or the result, so it stays fixed.
When SQL is not the layer
If the statements are right and the data is wrong, the problem is above Hibernate, in the mapping of results or in caching. If the statements are right and slow, the problem is the database, and the next tool is the plan, as in reading a query plan. The relevant references are the Hibernate user guide on logging and on statistics.


