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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 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.