How to Log SQL and Count Statements in Hibernate Apps
Log SQL in Hibernate with the right categories, show bind parameters, count statements with statistics and avoid the show_sql pitfalls in production.

Most Hibernate performance problems are not in Hibernate. They are in the SQL it was asked to run: too many statements, statements that fetch too much, or one statement per row where one for the page would do. You cannot fix what you cannot see, so the first tool is a log of the statements and the second is a count. This post covers both for Hibernate 7 under Spring Boot, explains what to look for in the output, and says what must stay out of production. The workflow that uses these tools to hunt a specific problem is in debugging Hibernate SQL.
The logger approach
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.orm.jdbc.bind=TRACE
spring.jpa.properties.hibernate.format_sql=trueorg.hibernate.SQL at DEBUG prints every statement. org.hibernate.orm.jdbc.bind at TRACE prints the value bound to each parameter, so you can see which id a where clause used. In versions before Hibernate 6 the bind logger had a different name, org.hibernate.type.descriptor.sql.BasicBinder, and a search result that shows it is out of date for this version. format_sql breaks the statement over lines, which makes a ten-way join readable.
Do not use spring.jpa.show-sql=true or hibernate.show_sql. It writes to standard output, ignores the logging framework, has no levels and cannot be filtered by logger or sent to a file. The logger approach goes through the same configuration as the rest of your application, and you can turn it on for one package or one environment. For general log configuration in Boot, see configuring log levels and files.
What to look for in the output
Read the log of a single request from start to end. Three patterns account for most problems.
The first is a repeated statement that differs only in the id: select ... from customer where id=? ten, a hundred, a thousand times. That is the N+1 problem, where a query loaded N rows and then each row's association was loaded separately. The fix is a join fetch, an entity graph, or batch fetching, covered in fixing N+1. The second is a statement that selects far more columns or rows than the page uses, such as select * over a table with a large text column, which a projection fixes. The third is an update statement for an entity you only read, which means something modified a managed object, or a mutable type that Hibernate considers dirty on every flush. Look for statements right before a commit that you cannot explain.
Also note the order. A write that appears after a read that should have seen it, or a flush in the middle of a method, explains puzzling behaviour with transactions.
Count statements
A log is easy to read for one request and hard to total. Hibernate's statistics count for you:
spring.jpa.properties.hibernate.generate_statistics=trueStatistics stats = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
stats.clear();
service.loadDashboard(userId);
System.out.println("statements: " + stats.getPrepareStatementCount());
System.out.println("entities loaded: " + stats.getEntityLoadCount());
System.out.println("flushes: " + stats.getFlushCount());The statement count is the number worth asserting in a test. A test that loads the dashboard and asserts getPrepareStatementCount() <= 4 fails the day someone adds a lazy association to the template, which is the regression you are trying to prevent. The technique, applied across a test suite, is in detecting N+1 queries in tests. Statistics add overhead, so enable them in tests and in diagnosis, not as a standing production setting.
Slow queries
spring.jpa.properties.hibernate.log_slow_query=25The value is a threshold in milliseconds. Hibernate logs the text of any statement slower than that, with its duration, on a dedicated logger. It finds the query that matters without logging all of them, and it is cheap enough to run in a staging environment. Take what it reports to the database, run explain on it, and read the plan; hibernate statistics and slow query logging goes deeper.
Production cautions
Statement logging has three costs. Volume: a busy service writes millions of lines an hour, and the log pipeline and the disk pay for it. Privacy: bind-parameter tracing writes customer data, emails and sometimes tokens into the log, which may breach your data protection rules and certainly widens who can read it. And speed: formatting and writing every statement slows the request. Keep org.hibernate.SQL and the bind logger at their defaults in production, switch them on temporarily for one instance while diagnosing, and switch them off again. If you need permanent visibility, count statements per request as a metric, which carries no data and costs almost nothing.
Alternatives
A JDBC-level proxy such as datasource-proxy or P6Spy logs the SQL that actually reached the driver, including bound values already substituted, and works with any persistence layer. It is useful when you suspect Hibernate is not the only source of statements, or when you want statement counts in a test without Hibernate's statistics. A database-side view such as pg_stat_statements in PostgreSQL shows the same information from the other end, aggregated across all clients, which is where you see the cumulative cost of a statement and not one request's share.
Pitfalls
The statement in the log is the one Hibernate prepared, with ? placeholders. It is not what you can paste into a console without substituting the bound values, and substituting by hand is how people debug the wrong query. Statement counts include inserts and updates, so a test about reads should isolate them. Batching changes the count: ten inserts sent as one batch show as one prepared statement but ten executions. And log output lags behind: if a request seems to run no SQL, check that the transaction has flushed, since Hibernate delays writes until commit or until a query needs them.
Reading a log line by line
Take a short real example. A request to show an order produces these statements, here shortened:
select o.id, o.status, o.customer_id from orders o where o.id=?
select c.id, c.name from customer c where c.id=?
select l.id, l.sku, l.order_id from order_line l where l.order_id=?
select p.id, p.title from product p where p.id=?
select p.id, p.title from product p where p.id=?
select p.id, p.title from product p where p.id=?Read it in order. The first line loads the order. The second loads its customer, which was a lazy association touched by the template. The third loads the lines. The last three load one product each for three lines, the classic N+1 shape: the same statement repeated with different ids. Six statements for a page that needs one join is already worth a fix, and with fifty lines it would be fifty-four. The count alone would have told you something was wrong, and the log tells you where.
Make this a routine. Whenever you add a screen or an endpoint, load it once with the SQL log on, count the statements, and ask whether the number grows with the data. If it does, fix it before it ships. It takes a minute and prevents the incident that arrives six months later when the table has grown.
When this does not apply
If the slowness is outside the database, in serialisation or a remote call, no amount of SQL logging will find it; profile instead, as described in finding slow endpoints. The logging options are listed in the Hibernate user guide on logging, and Spring Boot's own settings are in the logging reference.


