A Spring Java testing library for detecting the N+1 query problem in Hibernate-based applications.
The N+1 query problem is a common performance issue in ORM frameworks like Hibernate. It occurs when an application executes one query to fetch a list of entities (the "1"), and then, for each entity, executes an additional query (the "N") to fetch related data. This can lead to a large number of unnecessary database queries, severely impacting performance.
This library provides utilities to detect and assert the presence of the N+1 query problem in your Spring/Hibernate integration tests. It helps you:
- Monitor Hibernate statistics during test execution
- Assert the number of queries executed
- Fail tests if the N+1 problem is detected
-
Add the library to your project
- When available on Maven Central, add the following dependency to your
pom.xml:<dependency> <groupId>it.fabioformosa</groupId> <artifactId>n-plus-one-query-problem-detector</artifactId> <version>REPLACE_WITH_LATEST_VERSION</version> <scope>test</scope> </dependency>
- For Gradle:
testImplementation 'it.fabioformosa:n-plus-one-query-problem-detector:REPLACE_WITH_LATEST_VERSION' - Currently: The library is not yet on Maven Central. Clone this repository and run
./gradlew publishToMavenLocalto install it locally, then use the dependency as above.
- When available on Maven Central, add the following dependency to your
-
Enable Hibernate statistics
- In your
application.properties(test profile):spring.jpa.properties.hibernate.generate_statistics=true
- In your
-
Write your test
- Inject
NPlusOneQueryProblemDetectorinto your test class. - Use
startMonitoring()andstopMonitoring()to bracket the code you want to monitor. - Use the assertion utilities to check for N+1 problems.
Example:
@Autowired private NPlusOneQueryProblemDetector detector; @Test void testNPlusOne() { detector.startMonitoring(); // ... your code that may trigger N+1 ... detector.stopMonitoring(); NPlusOneQueryProblemAssertions.assertThat(detector).hasCountedMaxQueries(2); }
- Inject
This project is documented as a devlog, showing how an idea can turn into a project. Follow the development journey on YouTube:
- YouTube Channel: bitaligners
- Devlog Playlist: From Idea to Project: N+1 Query Problem Detector
This project is licensed under the Apache License 2.0.
