java
43 lines · 8 steps
Solving GraphQL N+1 with batch mapping in Spring
A Spring GraphQL controller resolves queries, batches author lookups to avoid N+1, and computes a derived field.
Explained by
highlit
1@Controller
2public class BookController {
3
4 private final BookService bookService;
5 private final AuthorService authorService;
6
7 public BookController(BookService bookService, AuthorService authorService) {
8 this.bookService = bookService;
9 this.authorService = authorService;
10 }
11
12 @QueryMapping
13 public Book bookById(@Argument String id) {
14 return bookService.findById(id)
15 .orElseThrow(() -> new BookNotFoundException(id));
16 }
17
18 @QueryMapping
19 public Page<Book> books(@Argument int page, @Argument int size, @Argument String genre) {
20 return bookService.search(genre, PageRequest.of(page, size));
21 }
22
23 @BatchMapping(typeName = "Book", field = "author")
24 public Map<Book, Author> author(List<Book> books) {
25 Set<String> authorIds = books.stream()
26 .map(Book::getAuthorId)
27 .collect(Collectors.toSet());
28
29 Map<String, Author> authorsById = authorService.findAllById(authorIds).stream()
30 .collect(Collectors.toMap(Author::getId, Function.identity()));
31
32 return books.stream()
33 .filter(book -> authorsById.containsKey(book.getAuthorId()))
34 .collect(Collectors.toMap(
35 Function.identity(),
36 book -> authorsById.get(book.getAuthorId())));
37 }
38
39 @SchemaMapping(typeName = "Book")
40 public String displayTitle(Book book) {
41 return book.getTitle() + " (" + book.getPublicationYear() + ")";
42 }
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Batch mapping resolves a nested field for many parents in one call, eliminating per-record N+1 queries.
- 2Building a lookup map keyed by id turns repeated service calls into a single bulk fetch plus in-memory joins.
- 3Schema mappings let you expose computed fields that don't exist on the underlying entity.
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
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 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
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 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/solving-graphql-n-1-with-batch-mapping-in-spring-explained-java-bc16/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.