Hibernate: Count the queries in a test to stop N+1 coming back

An assertion on query count turns a performance rule into something CI can enforce.

Code
@Test
void listEndpointIssuesOneQuery() {
    var stats = sessionFactory.getStatistics();
    stats.clear();

    service.recentOrders();

    assertThat(stats.getPrepareStatementCount()).isEqualTo(1);
}
Output
Expected: 1
Actual:   501

The test fails the day someone removes the join fetch.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11