java
16 lines · 5 steps
Killing N+1 queries with @EntityGraph in Spring
How Spring Data JPA repository methods eagerly fetch related entities in a single query using entity graphs.
Explained by
highlit
1@Repository
2public interface OrderRepository extends JpaRepository<Order, Long> {
3
4 @EntityGraph(attributePaths = {"customer", "lineItems", "lineItems.product"})
5 @Query("select o from Order o where o.status = :status")
6 List<Order> findByStatusWithDetails(@Param("status") OrderStatus status);
7
8 @EntityGraph(attributePaths = {"customer", "lineItems"})
9 Optional<Order> findWithDetailsById(Long id);
10
11 @EntityGraph(attributePaths = {"lineItems", "lineItems.product"})
12 Page<Order> findByCustomerId(Long customerId, Pageable pageable);
13
14 @EntityGraph(value = "Order.withShipments", type = EntityGraph.EntityGraphType.LOAD)
15 List<Order> findByPlacedAtBetween(Instant from, Instant to);
16}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1@EntityGraph declares which associations to fetch eagerly per query, sidestepping the N+1 problem without changing entity mappings.
- 2attributePaths accepts dotted paths like lineItems.product to fetch nested associations several levels deep.
- 3Named entity graphs and LOAD versus FETCH types let you reuse and fine-tune eager-loading strategy across methods.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/killing-n-1-queries-with-entitygraph-in-spring-explained-java-1b33/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.