Skip to lesson

Counting queries in tests and logs

A ShopLite page fixed to send 1 statement gets slow again when a teammate adds one innocent line. The team needs a number that fails the build, and tools that show how slow each statement is.

Hibernate Statistics in a test

Statistics is a Hibernate object that counts what Hibernate did since it was last cleared: statements prepared, entities loaded and collections fetched.

A test can ask Hibernate how many statements a call sent. Example 1 asserts that the ShopLite order report needs exactly one.

Example 1 · src/test/java/com/shoplite/lab/web/OrderReportQueryCountTest.java

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// src/test/java/com/shoplite/lab/web/OrderReportQueryCountTest.javapackage com.shoplite.lab.web;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.hibernate.SessionFactory;import org.hibernate.stat.Statistics;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;
import jakarta.persistence.EntityManagerFactory;
@SpringBootTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")class OrderReportQueryCountTest {
    @Autowired    private OrderReportService service;
    @Autowired    private EntityManagerFactory emf;
    private Statistics statistics;
    @BeforeEach    void resetStatistics() {        statistics = emf.unwrap(SessionFactory.class).getStatistics();        statistics.clear();    }
    @Test    void orderLinesUseOneQuery() {        List<String> lines = service.orderLines();
        assertThat(lines).hasSize(16).contains("14 Ravi Kumar SHIPPED");        assertThat(statistics.getPrepareStatementCount())                .as("SQL statements for the order report")                .isEqualTo(1);    }}
// OrderReportService.java (fragment): the version under test/** One line per order: "14 Ravi Kumar SHIPPED". */public List<String> orderLines() {    return orders.findAllWithCustomer().stream()            .map(o -> o.getId() + " " + o.getCustomer().getFullName() + " " + o.getStatus())            .toList();}
Sample output
$ mvn test -Dtest=OrderReportQueryCountTest
...
DEBUG SQL - select o1_0.order_id,o1_0.address_id,c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone,o1_0.ordered_at,o1_0.status from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id order by o1_0.order_id
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 22.70 s -- in com.shoplite.lab.web.OrderReportQueryCountTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

What this code does

  • statistics.clear() in @BeforeEach starts every test at zero. After service.orderLines(), getPrepareStatementCount() is exactly the statements that call sent.
  • The service uses findAllWithCustomer() (a join fetch), so the one logged SELECT is the whole report and the test passes.

A test turns the counters on with spring.jpa.properties.hibernate.generate_statistics=true, gets the object with entityManagerFactory.unwrap(SessionFactory.class).getStatistics(), and calls clear() before the code under test. After the call, getPrepareStatementCount() is the number of SQL statements sent. The test runs against the real MySQL test database, because only a real run shows the real SQL.

Statistics count for the whole application, not per thread. Tests that run in parallel in the same context would mix their numbers, so keep query-count tests in classes that run one test at a time (the JUnit default).

A test that fails when the query count grows

A query-count test asserts the exact number of SQL statements that a use case sends, so the build fails as soon as someone brings an N+1 back.

Example 2 runs the same test against the version a teammate wrote first: the mapper reads o.getCustomer().getFullName() on unfetched orders, and the build fails.

Example 2 · The same test catches the N+1 version

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// OrderReportService.java (fragment): the version a teammate wrote firstpublic List<String> orderLines() {    return orders.findAllByOrderByIdAsc().stream()                    // no fetch of the customer            .map(o -> o.getId() + " " + o.getCustomer().getFullName() + " " + o.getStatus())            .toList();}
// terminal: same test, unchangedmvn test -Dtest=OrderReportQueryCountTest
Sample output
$ mvn test -Dtest=OrderReportQueryCountTest
...
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 20.59 s <<< FAILURE! -- in com.shoplite.lab.web.OrderReportQueryCountTest
[ERROR] com.shoplite.lab.web.OrderReportQueryCountTest.orderLinesUseOneQuery -- Time elapsed: 2.496 s <<< FAILURE!
org.opentest4j.AssertionFailedError: 
[SQL statements for the order report] 
expected: 1L
 but was: 8L

[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   OrderReportQueryCountTest.orderLinesUseOneQuery:40 [SQL statements for the order report] 
expected: 1L
 but was: 8L
[INFO] 
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

What this code does

  • The service now sends 1 + 7 statements, so the assertion fails with the real number: "expected: 1L but was: 8L".
  • The description in as(...) names the use case, so whoever breaks it sees which page got slower and by how much.

The failure message reads "expected: 1L but was: 8L". Assert the exact number, not "at most 10": an exact number fails on any change, including a new extra query that is still under the limit, and the message tells you how many statements appeared. When a change is intended, you update the number in the same commit, and the reviewer sees it.

Put the use case in the assertion description too (as("SQL statements for the order report")), so the failure explains itself. The ShopLite project at the end of this module adds such tests for the product list and the category tree.

A proxy DataSource: SQL counts per request

datasource-proxy (net.ttddyy:datasource-proxy) is a library that wraps the real DataSource in a proxy, so every SQL statement can be logged and counted per thread before it reaches the driver.

A test counts one call, but a running app needs a count per HTTP request. Example 3 logs one line per request with a small servlet filter.

Example 3 · datasource-proxy: one log line per request

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
<!-- pom.xml (fragment) --><dependency>    <groupId>net.ttddyy</groupId>    <artifactId>datasource-proxy</artifactId>    <version>1.11.1</version></dependency>
// src/main/java/com/shoplite/lab/web/SqlCountConfig.javapackage com.shoplite.lab.web;
import java.io.IOException;
import javax.sql.DataSource;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.config.BeanPostProcessor;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;import net.ttddyy.dsproxy.QueryCount;import net.ttddyy.dsproxy.QueryCountHolder;import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
/** Counts the SQL statements of every HTTP request. Turned on with shoplite.sql-count=true (dev only). */@Configuration@ConditionalOnProperty(name = "shoplite.sql-count", havingValue = "true")class SqlCountConfig {
    private static final Logger log = LoggerFactory.getLogger(SqlCountConfig.class);
    /** Wraps the real DataSource (HikariCP) in a counting proxy. */    @Bean    static BeanPostProcessor countingDataSource() {        return new BeanPostProcessor() {            @Override            public Object postProcessAfterInitialization(Object bean, String beanName) {                if (bean instanceof DataSource dataSource) {                    return ProxyDataSourceBuilder.create(dataSource)                            .name("shoplite")                            .countQuery()                            .build();                }                return bean;            }        };    }
    /** Logs one line per request: method, path and the number of SQL statements. */    @Bean    OncePerRequestFilter sqlCountFilter() {        return new OncePerRequestFilter() {            @Override            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,                                            FilterChain chain) throws ServletException, IOException {                QueryCountHolder.clear();                try {                    chain.doFilter(request, response);                } finally {                    QueryCount count = QueryCountHolder.getGrandTotal();                    log.info("{} {} -> {} SQL statements ({} select)", request.getMethod(),                            request.getRequestURI(), count.getTotal(), count.getSelect());                    QueryCountHolder.clear();                }            }        };    }}
// terminaljava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --shoplite.sql-count=truecurl localhost:8080/lab/reports/orders-oldcurl localhost:8080/lab/reports/orderscurl localhost:8080/lab/order-views/14
Sample output
INFO  SqlCountConfig - GET /lab/reports/orders-old -> 8 SQL statements (8 select)
INFO  SqlCountConfig - GET /lab/reports/orders -> 1 SQL statements (1 select)
INFO  SqlCountConfig - GET /lab/order-views/14 -> 2 SQL statements (2 select)

What this code does

  • The BeanPostProcessor replaces the HikariCP DataSource bean with a counting proxy; Hibernate and Spring never notice. countQuery() keeps the counts per thread in QueryCountHolder.
  • The filter clears the counts before the request and logs them after it: 8 for the N+1 report, 1 after the fix, 2 for the DTO view of one order.

Example 3 wraps HikariCP's DataSource with a BeanPostProcessor and logs the counts per request. The old report shows 8 statements, the fixed one 1. This works for every query source, Hibernate, JdbcClient or plain JDBC, and it costs little. Turn it on with a property only in dev or a load-test environment.

Statistics answer "how many statements did Hibernate prepare in this test?"; the proxy answers "how many did this HTTP request send?". In dev, click through the app's pages and watch for request lines with large or growing numbers.

Hibernate Statistics and datasource-proxy count. Neither tells you whether one statement is slow: that is the database's job, next section.

MySQL's slow query log and EXPLAIN on Hibernate's SQL

The slow query log is a MySQL file that records every statement slower than long_query_time seconds (10 by default), with its time and the number of rows it examined.

A statement count does not say whether one statement is slow. Example 4 catches a slow page query in the log, and Example 5 explains it with EXPLAIN.

Example 4 · The slow query log catches a full scan

Runs in: a MySQL test server with a large orders table

SQL
-- mysql, as an admin, on a test server (512,020 rows in orders)SET GLOBAL slow_query_log = ON;SET SESSION long_query_time = 0.1;      -- log anything slower than 0.1 s (the default is 10 s)
-- the statement Hibernate logged for "newest PLACED orders, page 0, size 20"select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.status='PLACED' order by o1_0.ordered_at desc limit 0,20;
SET GLOBAL slow_query_log = OFF;-- then read the end of the slow log file (SHOW VARIABLES LIKE 'slow_query_log_file' gives its path)
Sample output
# Time: 2026-10-16T07:06:53.888544Z
# User@Host: root[root] @ localhost [127.0.0.1]  Id:  8635
# Query_time: 0.326164  Lock_time: 0.000005 Rows_sent: 20  Rows_examined: 512020
use w_perf_2000;
SET timestamp=1792134413;
select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.status='PLACED' order by o1_0.ordered_at desc limit 0,20;

What this code does

  • Query_time: 0.326164 is above the 0.1 s threshold, so MySQL wrote the statement to the slow log with its timing.
  • Rows_examined: 512020 against Rows_sent: 20 is the warning sign: MySQL read the whole table to return one page.

Example 5 · EXPLAIN before and after an index on (status, ordered_at)

Runs in: a MySQL test server with a large orders table

SQL
-- the slow statement, with EXPLAIN in frontEXPLAIN select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.status='PLACED' order by o1_0.ordered_at desc limit 0,20;
CREATE INDEX ix_orders_status_ordered ON orders (status, ordered_at);
EXPLAIN select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.status='PLACED' order by o1_0.ordered_at desc limit 0,20;
Sample output
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-----------------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra                       |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-----------------------------+
|  1 | SIMPLE      | o1_0  | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 510822 |    10.00 | Using where; Using filesort |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-----------------------------+
+----+-------------+-------+------------+------+--------------------------+--------------------------+---------+-------+-------+----------+---------------------+
| id | select_type | table | partitions | type | possible_keys            | key                      | key_len | ref   | rows  | filtered | Extra               |
+----+-------------+-------+------------+------+--------------------------+--------------------------+---------+-------+-------+----------+---------------------+
|  1 | SIMPLE      | o1_0  | NULL       | ref  | ix_orders_status_ordered | ix_orders_status_ordered | 42      | const | 18768 |   100.00 | Backward index scan |
+----+-------------+-------+------------+------+--------------------------+--------------------------+---------+-------+-------+----------+---------------------+

-- SHOW PROFILES: the same query with and without the index
| Duration   | Query
| 0.02776675 | select ... where o1_0.status='PLACED' order by o1_0.ordered_at desc limit 0,20   (with the index)
| 0.38317850 | select ... where o1_0.status='PLACED' order by o1_0.ordered_at desc limit 0,20   (index dropped)

What this code does

  • Before: type ALL, no key, about 510,822 rows, Using where; Using filesort: a full scan plus a sort of every PLACED order.
  • After: type ref on the new index and Backward index scan with no filesort; the page went from 0.38 s to 0.03 s.

On a test or staging server, turn the log on with a low threshold, run the app's pages, and read which statements appear. Example 4 caught a page query that examined all 512,020 rows of orders to return 20.

EXPLAIN in front of a SELECT shows MySQL's plan without running it. Copy the statement from the Hibernate log (with values for the ?) and prefix it. Read three columns first: type (ALL means a full table scan; ref or range means an index is used), rows (MySQL's estimate of rows read) and Extra (Using filesort means a separate sort step). In Example 5 the plan was ALL over 510,822 estimated rows with Using filesort. An index on (status, ordered_at) made it ref with a Backward index scan: MySQL reads the index from newest to oldest and stops after 20 rows, and the query went from 0.38 s to 0.03 s.

Predict the output

Read the EXPLAIN plan

Look at the columns of an EXPLAIN result. What does the plan say?

Round 1 of 2

The orders table has about 510,000 rows.

type: ALL
key: NULL
rows: 510822
Extra: Using where; Using filesort
Setting slow_query_log needs admin rights and affects the whole server. Do it on your own or a test server, and turn it off again.

Indexes for foreign-key and sort columns

A composite index is one index on several columns, such as (customer_id, ordered_at). MySQL can use it to filter by the first column and to read the rows already sorted by the next one.

A ShopLite list is usually filtered by a link and sorted by a date. Example 6 compares the automatic foreign-key index with a composite one.

Example 6 · A customer's order history: the foreign-key index and a composite index

Runs in: the ShopLite MySQL database

SQL
SHOW INDEX FROM orders;EXPLAIN select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.customer_id=2 order by o1_0.ordered_at desc;
CREATE INDEX ix_orders_customer_ordered ON orders (customer_id, ordered_at);EXPLAIN select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.customer_id=2 order by o1_0.ordered_at desc;SHOW INDEX FROM orders;
DROP INDEX ix_orders_customer_ordered ON orders;
Sample output
+--------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table  | Non_unique | Key_name           | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+--------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| orders |          0 | PRIMARY            |            1 | order_id    | A         |          16 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| orders |          1 | fk_orders_customer |            1 | customer_id | A         |           7 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| orders |          1 | fk_orders_address  |            1 | address_id  | A         |           9 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
+--------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
+----+-------------+-------+------------+------+--------------------+--------------------+---------+-------+------+----------+----------------+
| id | select_type | table | partitions | type | possible_keys      | key                | key_len | ref   | rows | filtered | Extra          |
+----+-------------+-------+------------+------+--------------------+--------------------+---------+-------+------+----------+----------------+
|  1 | SIMPLE      | o1_0  | NULL       | ref  | fk_orders_customer | fk_orders_customer | 4       | const |    3 |   100.00 | Using filesort |
+----+-------------+-------+------------+------+--------------------+--------------------+---------+-------+------+----------+----------------+
+----+-------------+-------+------------+------+----------------------------+----------------------------+---------+-------+------+----------+---------------------+
| id | select_type | table | partitions | type | possible_keys              | key                        | key_len | ref   | rows | filtered | Extra               |
+----+-------------+-------+------------+------+----------------------------+----------------------------+---------+-------+------+----------+---------------------+
|  1 | SIMPLE      | o1_0  | NULL       | ref  | ix_orders_customer_ordered | ix_orders_customer_ordered | 4       | const |    3 |   100.00 | Backward index scan |
+----+-------------+-------+------------+------+----------------------------+----------------------------+---------+-------+------+----------+---------------------+
+--------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table  | Non_unique | Key_name                   | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+--------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| orders |          0 | PRIMARY                    |            1 | order_id    | A         |          16 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| orders |          1 | fk_orders_address          |            1 | address_id  | A         |           9 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| orders |          1 | ix_orders_customer_ordered |            1 | customer_id | A         |           7 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| orders |          1 | ix_orders_customer_ordered |            2 | ordered_at  | A         |          16 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
+--------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
ERROR 1553 (HY000) at line 1: Cannot drop index 'ix_orders_customer_ordered': needed in a foreign key constraint

What this code does

  • The automatic foreign-key index fk_orders_customer finds customer 2's rows (ref) but still sorts them (Using filesort). With (customer_id, ordered_at) the rows come out in order: Backward index scan.
  • InnoDB dropped fk_orders_customer because the composite index can serve the foreign key, so the new index cannot be dropped without one to replace it.

An index is a sorted copy of one or more columns with pointers to the rows, so MySQL can find and order rows without reading the whole table (Section 12 covered them). Two kinds matter most for JPA code: indexes on foreign-key columns, used by every lazy load and every join (where customer_id=?), and composite indexes whose last column is the sort column of a list. InnoDB creates an index on each foreign-key column automatically: fk_orders_customer in Example 6. It finds a customer's orders, but order by ordered_at desc still needs Using filesort; the composite index (customer_id, ordered_at) serves both the filter and the order.

Example 6 also shows a MySQL detail: once the composite index exists, InnoDB drops its own fk_orders_customer index, because the new index starts with customer_id and can serve the foreign key. That is why DROP INDEX then fails with "needed in a foreign key constraint". In ShopLite such indexes are added through migrations, as the Flyway module shows.

Fix the error

Fix the DROP INDEX error

Read the real error, then pick the line that fixes it.

The only index on the foreign-key column customer_id is dropped.

-- orders.customer_id is a foreign key
DROP INDEX fk_orders_customer ON orders;

Error

Cannot drop index 'fk_orders_customer': needed in a foreign key constraint

Next step

Check your understanding

12 quick questions