Query Analyzer: Framework-Agnostic, Confidence-Based N+1 Detection for the JVM
Abstract
The N+1 query problem (issuing one database query per element of a collection instead of a single batched query) is among the most common and costly performance defects in data-access code, yet tool support on the Java Virtual Machine (JVM) is fragmented. Raw Java Database Connectivity (JDBC) interceptors log statements but do not detect anti-patterns; test-time assertion libraries detect N+1 only inside unit tests, are typically tied to Hibernate, and flag any repeated query, producing false positives on legitimate patterns such as pagination and polling. We present Query Analyzer, an open-source tool that automatically detects N+1 queries, analyzes their query plans, and suggests fixes. It intercepts queries at the JDBC layer, so it works across frameworks (Hibernate, Spring Data JPA, MyBatis, jOOQ, plain JDBC); it runs both as a @NoNPlusOne JUnit 5 regression guard and as a production servlet filter with per-endpoint reporting; and it uses a confidence model with explicit false-positive suppression to separate true N+1s from legitimate repetition. It additionally analyzes EXPLAIN plans and emits framework-specific fix suggestions. Dropped into unmodified real-world applications—Spring PetClinic and a third-party many-to-many sample—Query Analyzer detects real N+1s at high confidence, each pinpointed to a stack frame, and its own suggested fix eliminates them. On a controlled benchmark it cleanly separates true N+1s from legitimate repetition (pagination, polling, batched reads) where a count-based rule and the live JPlusOne detector cannot (F1 1.00 versus 0.57 and 0.67 on the suite). Query Analyzer is on Maven Central and ships a one-command reproduction package.