Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

In Spring for GraphQL, how do you implement a query books and a field author on Book, and how do you avoid an N+1 problem for author?

We define the schema in src/main/resources/graphql/*.graphqls, resolve the books query with a @QueryMapping List<Book> books() method in a @Controller, and bind any arguments with @Argument. A @SchemaMapping Author author(Book book) method resolves the field, but it runs once per book, so 100 books cause 100 author lookups, the N+1 problem. Replacing it with @BatchMapping Map<Book, Author> author(List<Book> books) lets Spring for GraphQL collect all books through a DataLoader and load their authors in one call.

Why this question is asked

GraphQL lets the client choose which fields it wants, and the server resolves each field with a small function. That flexibility is the point of GraphQL, and it is also where performance goes wrong: a field resolver that looks harmless can be called hundreds of times per request. Interviewers ask this question because it covers the basic annotation model of Spring for GraphQL and its most common performance trap in one go. In this answer, we will recap how GraphQL resolves fields, write the schema and the query, add the author field, watch the N+1 problem happen, and fix it with @BatchMapping.

1A Quick Recap of How GraphQL Resolves a Query

A GraphQL server has a schema: types with fields, plus the special Query type whose fields are the entry points. When a request arrives, the engine (graphql-java underneath Spring for GraphQL) walks the query tree. For each field it calls a data fetcher, the function that returns that field's value, passing it the parent object. For simple fields like title, the default fetcher just reads a property of the parent. For fields like author, we provide our own fetcher.

Spring for GraphQL connects annotated controller methods to the schema: the method name, or the annotation's attributes, says which type and field it resolves. The schema files are picked up automatically from src/main/resources/graphql/ with the extension .graphqls or .gqls.

2Defining the Schema and the books Query

Here is the schema and the controller for the query. The records hold just enough data for the example.

Java
# src/main/resources/graphql/schema.graphqls
type Query {
books: [Book!]!
bookById(id: ID!): Book
}
type Book { id: ID! title: String! author: Author! }
type Author { id: ID! name: String! }
// Java
record Book(String id, String title, String authorId) {}
record Author(String id, String name) {}
@Controller
class BookController {
private final BookRepository books;
private final AuthorClient authors;
BookController(BookRepository books, AuthorClient authors) { this.books = books; this.authors = authors; }
@QueryMapping // resolves Query.books
List<Book> books() { return books.findAll(); }
@QueryMapping // resolves Query.bookById
Book bookById(@Argument String id) { return books.findById(id).orElse(null); }
}

@QueryMapping is a shortcut for @SchemaMapping(typeName = "Query"), and the field name defaults to the method name. @Argument binds the GraphQL argument id to the method parameter, converting types as needed. Notice that Book has an authorId but no author: the schema's author field must be resolved separately.

3Resolving author With @SchemaMapping and the N+1 Problem

The obvious way to resolve Book.author is a @SchemaMapping method that takes the parent Book.

Java
@SchemaMapping // typeName inferred from the parameter: Book
Author author(Book book) {
return authors.findById(book.authorId()); // one call per book
}
// query { books { title author { name } } } with 100 books:
// 1 call -> books.findAll()
// 100 calls -> authors.findById("a1"), authors.findById("a2"), ...
// total: 101 calls for one request
Calls made for 100 books
Resolver stylebooks()author lookupsTotal
@SchemaMapping, one per book1100101
@BatchMapping, one per level11 (100 ids)2

This is correct but slow. GraphQL calls the author fetcher once for every Book in the list, so the number of author lookups grows with the number of books: one query for the list, plus N for the authors. That is the N+1 problem. If the author lookup is a database query, it is 100 round trips; if it is a REST call to an author service, it can easily turn a 50 ms request into a 2-second one.

4Fixing It With @BatchMapping

@BatchMapping tells Spring for GraphQL that this field should be loaded in batches. Instead of one Book, the method receives all the Books for which the field is needed in the current request, and returns a map from each Book to its Author.

Java
@BatchMapping // resolves Book.author for many books at once
Map<Book, Author> author(List<Book> books) {
Set<String> ids = books.stream().map(Book::authorId).collect(Collectors.toSet());
Map<String, Author> byId = authors.findAllById(ids).stream()
.collect(Collectors.toMap(Author::id, a -> a)); // one call with all ids
return books.stream().collect(Collectors.toMap(b -> b, b -> byId.get(b.authorId())));
}
// same query with 100 books: 1 call for books + 1 call for authors = 2 calls
Step throughHow @BatchMapping batches the author field
GraphQL engineDataLoaderauthor(List<Book>)Author service
load(book1) ... load(book100)
dispatch at end of level
call once with 100 books
findAllById(ids)
authors
Map<Book, Author>
complete 100 author fields

7 messages in order. Play them, or step through them one at a time.

Under the hood, Spring registers a DataLoader for this field. A DataLoader, from the java-dataloader library that graphql-java uses, is a per-request object that collects keys while the engine walks one level of the query, and then calls a batch function once with all collected keys. Spring for GraphQL creates that batch function from our @BatchMapping method, so we never touch the DataLoader API directly.

Two details matter. The Book objects are used as map keys, so they need proper equals() and hashCode(); records provide them. And we must not declare both a @SchemaMapping and a @BatchMapping for the same field, since only one fetcher can resolve it. The method may also return a List in the same order as the input, or a reactive Flux or Mono of the map.

5Follow-up questions

What if the parent type name cannot be inferred from the method?

Set it explicitly: @SchemaMapping(typeName = "Book", field = "author") or @BatchMapping(typeName = "Book", field = "author"). This is needed when the parameter type does not match the GraphQL type name, or when the method name differs from the field name.

Is the DataLoader cache shared between requests?

No. DataLoaders are created per request, so their cache only deduplicates keys within one request; two books by the same author in one response cause one lookup, but the next request starts fresh. Cross-request caching belongs in the service or repository layer, where expiry and invalidation can be controlled.

How do you test that the N+1 problem is really gone?

Use GraphQlTester (for example with @GraphQlTest) to run the query against the controller, and mock or spy the author client to assert it is called once with all ids. Logging the SQL count or using a query-count assertion in an integration test gives the same guarantee for database lookups.

6Conclusion

In this answer, we built a Spring for GraphQL API with the schema in src/main/resources/graphql, a @QueryMapping method for books and @Argument for parameters. We saw that a @SchemaMapping resolver for Book.author runs once per book and produces the N+1 problem, 101 calls for 100 books, and fixed it with @BatchMapping, which receives all books of the request and returns a Map<Book, Author>, backed by a per-request DataLoader that turns the work into a single author lookup.

What to say in the interviewAbout 90 seconds aloud

Open with

In Spring for GraphQL I start with the schema in src/main/resources/graphql, for example schema.graphqls, with a Query type that has books returning a list of Book, and Book having id, title and author.

Then, if they want more

Then I write a @Controller. A method annotated with @QueryMapping named books returns the List<Book>; it resolves Query.books, and if the query had arguments I would bind them with @Argument. Book has only an authorId, so the author field needs its own resolver. The straightforward way is a @SchemaMapping method author(Book book) that looks up the author for one book.

The problem is that GraphQL calls it once per book, so a list of 100 books means one call for the list and 100 author calls, the N+1 problem. The fix is @BatchMapping: I write author(List<Book> books) returning Map<Book, Author>.

Spring registers a DataLoader for the field, which collects every book that needs an author while the engine walks that level of the query, then calls my method once, so I can fetch all authors with one findAllById and map them back. That makes it two calls in total.

The books are map keys, so they need equals and hashCode, which records give me, and I would verify it in a GraphQlTester test by asserting the author client is called once.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In Spring for GraphQL, how do you implement a query books and a field author on Book...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/c9043c42b1/