Skip to content
javahacks.dev
Hibernate

How to Use Hibernate Statistics and Slow Query Logging

Use Hibernate statistics and slow query logging to find costly queries: enable generate_statistics, read counters, set a threshold and expose metrics.

5 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the Hibernate, OpenJDK, Redis and Grafana logos.

Hibernate can tell you what it is doing: how many queries ran, which was the slowest, how many entities were loaded and how effective the caches are. Those numbers are the quickest way to find a request that issues two hundred queries, and a slow-query threshold turns the worst of them into log lines. This guide shows how to switch statistics on, read them in code, log slow queries, publish the counters as metrics, decide where to run them and when to prefer the database's own tools. The settings work on Hibernate 7 with Spring Boot 4.

Turn statistics on

properties
spring.jpa.properties.hibernate.generate_statistics=true

The counters live on the session factory and cover queries executed, entities loaded, inserted, updated and deleted, collection loads, second-level cache hits and misses, and flush counts. They start at zero when the application starts and accumulate until cleared. The switch is off by default because collecting them adds a little synchronisation on shared counters, which is covered under cost below.

Read them in code

java
@Component
class StatsReporter {

    private final Statistics stats;

    StatsReporter(EntityManagerFactory emf) {
        this.stats = emf.unwrap(SessionFactory.class).getStatistics();
    }

    String summary() {
        return "queries=%d, slowest=%dms (%s)".formatted(
            stats.getQueryExecutionCount(),
            stats.getQueryExecutionMaxTime(),
            stats.getQueryExecutionMaxTimeQueryString());
    }
}

getQueryExecutionMaxTimeQueryString tells you which query was the slowest since the last reset, which is often all you need to find a culprit. stats.getEntityStatistics("com.example.Author") gives loads and fetches for one entity, useful for finding an entity that is loaded far more often than expected, a classic sign of an N plus 1 pattern. Expose the summary through a diagnostic endpoint protected like any other admin function, or write it to the log at the end of a test run.

Log slow queries

properties
spring.jpa.properties.hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS=250
logging.level.org.hibernate.SQL_SLOW=INFO

Any query slower than the threshold is logged at INFO under the org.hibernate.SQL_SLOW category, with its text and duration. A threshold of 200 to 500 milliseconds catches the worst offenders without flooding the log; lower it on a quiet development database and raise it for a batch job. This differs from statement logging, described in logging SQL: that prints everything and is for development, while the slow-query log is quiet unless something is slow and is suitable for longer use. The logged text contains placeholders, not values, so it is safe to ship to a log platform.

Publish metrics

Spring Boot with Micrometer exposes the counters as metrics when statistics are on:

properties
management.endpoints.web.exposure.include=health,metrics

Look for the metrics named hibernate.query.executions, hibernate.entities.loads and hibernate.second.level.cache.requests at /actuator/metrics. Graph them to spot regressions: a jump in statements per request after a deploy usually means a new N plus 1 pattern, whose cure is in N plus 1. Dividing the query counter by the request counter gives statements per request, a single number that is easy to alert on, and a stable service keeps it roughly constant.

Cost and scope

Statistics add synchronisation on shared counters and string work to remember the slowest query. The overhead is small but not zero, and it grows with concurrency because the counters are shared. A reasonable policy is on in development and test, where the numbers feed N plus 1 checks; on in staging, where the load is realistic; and in production either enabled for a diagnostic window or kept on only if you measured the cost on your own traffic. A flag that you can change without a redeploy makes the diagnostic window practical.

The database is the better production source

Hibernate sees the time from its side of the connection, which includes network latency, driver work and result mapping. PostgreSQL's pg_stat_statements extension and the slow-query log see the database's view, with plans and with the cost of the query when it ran. Use the Hibernate threshold to find which code issued a query, and the database to find out why it is slow, with explain analyze. A query that is fast in the database and slow in Hibernate points at mapping or at fetching too many rows, not at the index. For the JVM side of a slow request, see how the JVM works.

Using the counters in tests

Statistics make a useful assertion in an integration test. Clear the counters, call a service method, and assert that the query count is below a small number. A test that fails when a loop starts issuing a query per element catches an N plus 1 before review does. Keep the threshold exact enough to be meaningful, and update it knowingly when you add a legitimate query. Combine it with the techniques in detecting N plus 1 in tests.

Reset

stats.clear() zeroes the counters, handy before a measurement. Counters are cumulative since the last clear, so compare deltas around the operation you care about, not absolute values, and avoid clearing in production code paths that others read.

A short workflow for a slow request

When a request is slow, clear the statistics, make the request once and read the delta. If the query count is high, look at the entity loads to find which entity repeats, and fix the fetch plan. If the query count is low and the time is high, read the slowest query, run it with explain analyze in the database and look for a missing index or a large sort. If both are low, the time is elsewhere: serialisation, a remote call or locking. The statistics narrow the search to one of these three branches in a minute, which is their main value.

Second-level cache numbers

If you use the second-level cache, three counters decide whether it earns its place: hits, misses and puts. A hit ratio below about half for an entity means the cache holds data that is evicted before it is read again, and it costs memory for nothing. Read the ratio per region, not overall, and remember that a cache hit still has a cost in invalidation when the entity is updated often.

When statistics will not show the problem

Read-heavy services behind a cache may hide their slow queries until the cache is cold, so test with a cold cache too. Queries issued by native JDBC code, outside Hibernate, are invisible to these counters. The references are the Hibernate statistics section of the user guide and the Micrometer JVM and Hibernate bindings.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.