Setup and verification
JDK 21, Maven 3.9 or newer, Docker. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.
verify.py starts PostgreSQL itself. Running mvn test alone requires the matching database environment variables.
Verified on 2026-10-20 on Linux x86_64. Three records produce four statements in the slow path and one with a fetch join. With a fourth record the solution expects five versus one. This is not a blanket recommendation for paginated collection fetch joins.
An ORM can hide several SQL queries behind simple field access. The test stores three vehicles with one entry each, then clears the persistence context so previously loaded objects cannot conceal the problem. Hibernate statistics count statements against real PostgreSQL.
Package contents and individual files
01Read the domain contract
LAZY postpones loading a relationship. Calling getName can therefore issue another SQL query. A fetch join loads the required relationship in the same query. em.clear prevents the first-level cache from distorting the comparison.
package tutorial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@jakarta.persistence.Entity(name = "Vehicle")
class Vehicle {
@jakarta.persistence.Id
Long id;
String name;
public String getName() {
return name;
}
protected Vehicle() {}
Vehicle(long id, String name) {
this.id = id;
this.name = name;
}
}
@jakarta.persistence.Entity(name = "RecordEntry")
class RecordEntry {
@jakarta.persistence.Id
Long id;
@jakarta.persistence.ManyToOne(fetch = jakarta.persistence.FetchType.LAZY)
Vehicle vehicle;
protected RecordEntry() {}
RecordEntry(long id, Vehicle v) {
this.id = id;
this.vehicle = v;
}
}
02Start an isolated environment
Java 21 is the language baseline. Maven resolves dependencies from the POM. verify.py creates its own PostgreSQL instance on an available local port and removes only that container after testing.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.1.0</version></parent>
<groupId>learning</groupId><artifactId>tutorial</artifactId><version>1.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId></dependency>
</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
03Verify success and failure
Three records produce four statements in the slow path and one with a fetch join. With a fourth record the solution expects five versus one. This is not a blanket recommendation for paginated collection fetch joins.
package tutorial;
import static org.junit.jupiter.api.Assertions.*;
import jakarta.persistence.*;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
@Transactional
class LessonTest {
@PersistenceContext
EntityManager em;
@Test
void fetchJoinAvoidsExtraStatements() {
for (long i = 1; i <= 3; i++) {
var v = new Vehicle(i, "Vehicle " + i);
em.persist(v);
em.persist(new RecordEntry(i, v));
}
em.flush();
em.clear();
var stats = em
.getEntityManagerFactory()
.unwrap(SessionFactory.class)
.getStatistics();
stats.clear();
var slow = em
.createQuery(
"select e from RecordEntry e order by e.id",
RecordEntry.class
)
.getResultList();
var names = slow
.stream()
.map(e -> e.vehicle.getName())
.toList();
assertEquals(3, names.size());
assertEquals(4, stats.getPrepareStatementCount());
em.clear();
stats.clear();
var fast = em
.createQuery(
"select e from RecordEntry e join fetch e.vehicle order by e.id",
RecordEntry.class
)
.getResultList();
assertEquals(
names,
fast
.stream()
.map(e -> e.vehicle.getName())
.toList()
);
assertEquals(1, stats.getPrepareStatementCount());
}
}
Run / check
python3 verify.pyThree records produce four statements in the slow path and one with a fetch join. With a fourth record the solution expects five versus one. This is not a blanket recommendation for paginated collection fetch joins.
04Make a regression visible
Change a domain expectation and rerun the test. Maven must report failure. A skipped database test is not evidence. Restore the correct expectation afterwards.
05Extend the contract
Add a fourth record and adjust the expected statement count of the slow path.
06Explain the solution and its limits
The slow path performs one list query plus four lazy loads. The fetch join remains one query. This says nothing about pagination with collection fetch joins, which requires a separate query design. Copy solution/LessonTest.java over the test file and repeat the same verification.
All tests pass, including the additional solution expectation.
Your exercise
Add a fourth record and adjust the expected statement count of the slow path.
Show the solution and explanation
The slow path performs one list query plus four lazy loads. The fetch join remains one query. This says nothing about pagination with collection fetch joins, which requires a separate query design.
package tutorial;
import static org.junit.jupiter.api.Assertions.*;
import jakarta.persistence.*;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
@Transactional
class LessonTest {
@PersistenceContext
EntityManager em;
@Test
void fetchJoinAvoidsExtraStatements() {
for (long i = 1; i <= 4; i++) {
var v = new Vehicle(i, "Vehicle " + i);
em.persist(v);
em.persist(new RecordEntry(i, v));
}
em.flush();
em.clear();
var stats = em
.getEntityManagerFactory()
.unwrap(SessionFactory.class)
.getStatistics();
stats.clear();
var slow = em
.createQuery(
"select e from RecordEntry e order by e.id",
RecordEntry.class
)
.getResultList();
var names = slow
.stream()
.map(e -> e.vehicle.getName())
.toList();
assertEquals(4, names.size());
assertEquals(5, stats.getPrepareStatementCount());
em.clear();
stats.clear();
var fast = em
.createQuery(
"select e from RecordEntry e join fetch e.vehicle order by e.id",
RecordEntry.class
)
.getResultList();
assertEquals(
names,
fast
.stream()
.map(e -> e.vehicle.getName())
.toList()
);
assertEquals(1, stats.getPrepareStatementCount());
}
}
Project context and sources
This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.