0Pricing
GraphQL APIs with Spring Boot · レッスン

データResolverの実装

定義したGraphQLフィールドのデータをさまざまなソースから取得するResolver関数をSpring Bootで記述します。

「データResolverの実装」はCoddyKit上の無料GraphQL APIs with Spring Bootレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはGraphQL APIs with Spring Boot学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 GraphQL APIs with Spring Bootコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

What are Data Resolvers?

Welcome! In GraphQL, clients ask for specific data. But how does your server know where to get that data?

That's where Data Resolvers come in! A resolver is a function or method that knows how to fetch the data for a specific field in your GraphQL schema.

  • They act as the bridge between your schema and your data sources (like databases, APIs, or even simple in-memory lists).
  • Each field in your schema needs a resolver, implicitly or explicitly.

Resolvers in Spring for GraphQL

Spring for GraphQL makes implementing resolvers straightforward. It uses annotations to map Java methods directly to fields in your GraphQL schema.

You'll typically write these resolver methods inside Spring @Controller classes. Spring automatically scans these controllers and connects their methods to the GraphQL schema fields based on naming conventions or explicit annotations.

Your First Root Query Resolver

Let's create a simple resolver for a root query. We'll define a basic hello field that returns a greeting string.

First, imagine our schema has:

type Query {
  hello: String
}

Now, let's write the Java resolver:

import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

  @QueryMapping
  public String hello() {
    return "Hello from CoddyKit!";
  }
}

Resolving Custom Objects

Resolvers aren't just for simple strings. They can return custom Java objects too! Let's define a simple Book class and a resolver to return it.

Assume our schema has:

type Book {
  id: ID
  title: String
  author: String
}

type Query {
  firstBook: Book
}

Here's the Book class and a resolver:

import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

// A simple data class for our Book
record Book(String id, String title, String author) {}

@Controller
public class BookController {

  @QueryMapping
  public Book firstBook() {
    return new Book("book-1", "The Great Journey", "Alice Wonderland");
  }
}

Mocking Data Sources

For our examples, we won't connect to a real database. Instead, we'll use an in-memory list to simulate a data source. This keeps our code simple and focused on resolvers.

In a real application, your resolvers would interact with:

  • Databases (SQL, NoSQL)
  • Other REST or GraphQL APIs
  • Message queues
  • File systems

The resolver's job is just to get the data, no matter the source!

Implementing a List Resolver

Often, you'll want to return a list of objects. Our BookController can be updated to provide a list of books from a mock source.

If our schema has:

type Query {
  allBooks: [Book]
}

Here's how we'd implement the resolver:

import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.ArrayList;

record Book(String id, String title, String author) {}

@Controller
public class BookListController {

  private final List<Book> books = new ArrayList<>(List.of(
    new Book("b-1", "The Moonstone", "Wilkie Collins"),
    new Book("b-2", "Pride and Prejudice", "Jane Austen"),
    new Book("b-3", "1984", "George Orwell")
  ));

  @QueryMapping
  public List<Book> allBooks() {
    return books;
  }
}

Resolving by ID with Arguments

Queries often need arguments, like searching for a book by its ID. Resolvers can easily accept these arguments.

If our schema has:

type Query {
  bookById(id: ID!): Book
}

We use the @Argument annotation in Spring for GraphQL:

import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.ArrayList;

record Book(String id, String title, String author) {}

@Controller
public class BookByIdController {

  private final List<Book> books = new ArrayList<>(List.of(
    new Book("b-1", "The Moonstone", "Wilkie Collins"),
    new Book("b-2", "Pride and Prejudice", "Jane Austen")
  ));

  @QueryMapping
  public Book bookById(@Argument String id) {
    return books.stream()
      .filter(book -> book.id().equals(id))
      .findFirst()
      .orElse(null);
  }
}

Field-Level Resolvers

Sometimes, a field on an object itself needs a separate resolver. For example, if the author of a Book was a complex object needing its own lookup.

Let's say Book has an authorId, and we need to fetch the full Author object. We use @SchemaMapping for these non-root fields.

import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;

record Book(String id, String title, String authorId) {}
record Author(String id, String name) {}

@Controller
public class AuthorResolver {

  // This resolver is for the 'author' field on a 'Book' object
  @SchemaMapping
  public Author author(Book book) {
    // In a real app, you'd fetch from a data source using book.authorId()
    if ("auth-1".equals(book.authorId())) {
      return new Author(book.authorId(), "Wilkie Collins");
    }
    return new Author(book.authorId(), "Unknown Author");
  }
}

Complete Resolver Application

Let's put everything together into a runnable Spring Boot application! This example includes resolvers for listing books, finding a book by ID, and resolving an author for a book.

Try running this and querying it with a GraphQL client!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.ArrayList;

// Data classes
record Book(String id, String title, String authorId) {}
record Author(String id, String name) {}

@SpringBootApplication
public class GraphQLResolversApp {
  public static void main(String[] args) {
    SpringApplication.run(GraphQLResolversApp.class, args);
  }
}

@Controller
class BookDataController {

  private final List<Book> books = new ArrayList<>(List.of(
    new Book("b-1", "The Moonstone", "auth-1"),
    new Book("b-2", "Pride and Prejudice", "auth-2"),
    new Book("b-3", "1984", "auth-3")
  ));

  @QueryMapping
  public List<Book> allBooks() {
    return books;
  }

  @QueryMapping
  public Book bookById(@Argument String id) {
    return books.stream()
      .filter(book -> book.id().equals(id))
      .findFirst()
      .orElse(null);
  }

  // Field-level resolver for 'author' on 'Book'
  @SchemaMapping
  public Author author(Book book) {
    // Mocking author data lookup
    return switch (book.authorId()) {
      case "auth-1" -> new Author("auth-1", "Wilkie Collins");
      case "auth-2" -> new Author("auth-2", "Jane Austen");
      case "auth-3" -> new Author("auth-3", "George Orwell");
      default -> new Author(book.authorId(), "Unknown Author");
    };
  }
}

Understanding Resolver Mapping

Which of the following statements about GraphQL resolvers in Spring Boot are TRUE?

Recap: Your Resolver Journey

You've taken a big step in building GraphQL APIs!

  • We learned that resolvers are the core logic for fetching data.
  • Spring for GraphQL uses @Controller with @QueryMapping for root queries and @SchemaMapping for nested fields.
  • Resolvers can return simple types, custom objects, and lists.
  • You can pass arguments to resolvers using the @Argument annotation.

Next, you'll learn how to execute these queries using tools like GraphiQL!

よくある質問

「データResolverの実装」レッスンは無料ですか?

はい。「データResolverの実装」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、GraphQL APIs with Spring Bootコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 GraphQL APIs with Spring Bootコースには全4レッスンが含まれています。

「データResolverの実装」で何を学びますか?

定義したGraphQLフィールドのデータをさまざまなソースから取得するResolver関数をSpring Bootで記述します。 ブラウザで直接実行するハンズオンコードでGraphQL APIs with Spring Bootを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

GraphQL APIs with Spring Bootを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのGraphQL APIs with Spring Bootは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「データResolverの実装」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このGraphQL APIs with Spring Bootレッスンでコードを書いて実行できますか?

はい。すべてのGraphQL APIs with Spring Bootレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. カスタムデータ型の定義
  2. データResolverの実装
  3. 基本的なGraphQLクエリの実行
  4. GraphQLミューテーション:データの変更
← GraphQL APIs with Spring Bootに戻る