Queries and fetching
What you will learn
Select a query shape and fetch plan according to the response you need, then measure actual SQL.
- Distinguish JPQL, Criteria and native SQL.
- Explain N+1 and projection alternatives.
- Design bounded, stable pagination.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. JPA examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Model separate lookups versus prefetch
public class Main {
public static void main(String[] args) {var ids=java.util.List.of(1,2,3); int simulatedQueries=1;for(int id:ids) { simulatedQueries++; }System.out.println(simulatedQueries); System.out.println(1); }}Expected output:
41This is a cost illustration assuming separate misses, not an observed SQL count or timing.
Query shape
JPQL uses entity and attribute names; native SQL uses tables and columns. Criteria API builds query expressions programmatically (CriteriaBuilder, CriteriaQuery, Root, predicates); it does not automatically make a query faster. Bind values through named parameters rather than string concatenation; identifiers and sorting expressions require allowlists. Spring Data derives findBySku from the attribute name or accepts @Query. Constructor projections return selected values directly; the fully qualified record name in the JPQL constructor expression must match its argument types. Page can require a count query; Slice can avoid a total count. Use deterministic ordering by a unique key; concurrent writes can still shift offset pages.
N+1 and fetch plans
A list query followed by a separate lazy association lookup for each row can produce 1+N queries if each association is distinct and not cached. Actual count depends on batching, reuse and fetch plan. Join fetch and @EntityGraph request associated data; neither is a blanket promise of a fixed SQL count. A to-many fetch join multiplies rows; avoid paging over a collection fetch join, because Hibernate 7.2 may apply limits in memory. Prefer a page of IDs followed by a fetch query, or a DTO projection; preserve original page order if needed. The companion lab fails on collection-fetch pagination and records Hibernate statement counts. Measure in fresh contexts with controlled cache and batch settings; no performance gain is asserted here.
Stable projected page
public class Main { record View(String sku,int stock) {} public static void main(String[] args) {var rows=java.util.List.of(new View("B2",5),new View("A1",5),new View("C3",2));var page=rows.stream().sorted(java.util.Comparator.comparing(View::sku)).limit(2).map(View::sku).toList();System.out.println(page); }}Expected output:
[A1, B2]The real repository orders by SKU in the database; the tiny model only demonstrates ordering.
Repository queries and fetch plans
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/main/java/example/catalog/ProductRepository.java; use the companion lab README.
package example.catalog;import org.springframework.data.jpa.repository.*;import org.springframework.data.repository.query.Param;import org.springframework.data.domain.*;import jakarta.persistence.LockModeType;import java.util.*;public interface ProductRepository extends JpaRepository<Product,Long> { Optional<Product> findBySku(String sku); @EntityGraph(attributePaths="category") @Query("select p from Product p where p.stock >= :minimum order by p.sku") List<Product> stockedWithCategory(@Param("minimum") int minimum); @Query(value="select new example.catalog.ProductView(p.sku,p.stock,c.name) from Product p join p.category c where p.stock >= :minimum order by p.sku", countQuery="select count(p) from Product p where p.stock >= :minimum") Page<ProductView> summaries(@Param("minimum") int minimum, Pageable pageable); @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("select p from Product p where p.id = :id") Optional<Product> lockById(@Param("id") Long id);}Predicted behavior: Derived lookup, graph fetch, constructor projection and pessimistic query.
The count query omits order and matches the root filter.
Projection contract
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/main/java/example/catalog/ProductView.java; use the companion lab README.
package example.catalog;public record ProductView(String sku, int stock, String category) {}Predicted behavior: A three-field immutable response without lazy entity references.
No entity serialization is required.
Common mistakes
Do not concatenate untrusted values into JPQL, page over to-many fetch joins, or claim an exact N+1 count without measurement.
Practice
Sort three product views by unique SKU and take the second page of size two; print the remaining SKU.
Expected output:
[C3]Compare with the manual review criteria.
Official reading: Queries · Hibernate · Projections. ORM execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queries and fetching — knowledge check
JPA mapping and persistence reasoning.
What names does JPQL use?
What is a common cause of N+1?
Why avoid to-many fetch join pagination?
What does a Page often need that a Slice does not?
How should a query value be supplied?