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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Batch mapping resolves a nested field for many parents in one call, eliminating per-record N+1 queries.
  2. 2Building a lookup map keyed by id turns repeated service calls into a single bulk fetch plus in-memory joins.
  3. 3Schema mappings let you expose computed fields that don't exist on the underlying entity.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Solving GraphQL N+1 with batch mapping in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code