ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์
ใช้งานตัวจัดการ @QueryMapping และ @MutationMapping พร้อมการผูกอาร์กิวเมนต์และอินพุต
ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์ เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What a Data Fetcher Is
In Spring for GraphQL, every field in your schema is resolved by a data fetcher (the GraphQL-Java term for a resolver). When a client asks for a field, the engine invokes the fetcher bound to it.
Instead of registering raw DataFetcher beans, Spring lets you write annotated controller methods. The framework maps each method to a schema field and handles argument binding, return values, and async wrapping for you.
@QueryMappingresolves a field under the rootQuerytype.@MutationMappingresolves a field under the rootMutationtype.@SchemaMappingresolves any field (including nested object fields).
The Schema Drives Everything
Spring for GraphQL is schema-first. You declare your types and operations in an SDL file under src/main/resources/graphql/ (for example schema.graphqls), and your controller methods bind to those field names.
Consider this schema. The book and books fields live under Query, so each needs a @QueryMapping handler.
type Query {
books: [Book!]!
book(id: ID!): Book
}
type Mutation {
addBook(input: AddBookInput!): Book!
}
type Book {
id: ID!
title: String!
pages: Int!
}
input AddBookInput {
title: String!
pages: Int!
}Your First @QueryMapping
A @Controller class holds your handlers. By default, Spring infers the schema field name from the method name, so books() binds to the books query.
The return value is matched against the schema's return type. Here List<Book> satisfies [Book!]!.
@Controller
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
@QueryMapping
public List<Book> books() {
return bookService.findAll();
}
}Binding a Single Argument with @Argument
When a query field takes arguments, bind each one with @Argument. Spring matches the GraphQL argument name to the parameter name and coerces the value to the Java type.
For book(id: ID!), the ID scalar arrives as a String by default. Spring can also coerce it to Long if your parameter is typed that way.
@QueryMapping
public Book book(@Argument Long id) {
return bookService.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
}When Argument and Parameter Names Differ
Parameter-name matching depends on debug symbols being present in the compiled class. If they are stripped, or if you simply want a different Java name, set the argument name explicitly.
@Argument("id")binds the schema argumentidto whatever parameter you declare.- Compiling with the
-parametersflag (the Spring Boot starter parent enables it) keeps names available, so the explicit form is often optional.
@QueryMapping
public Book book(@Argument("id") Long bookId) {
return bookService.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));
}Binding Input Objects to a POJO
For mutations that accept an input object, you do not bind each field separately. Instead, @Argument binds the whole GraphQL input type to a Java class. Spring populates the object field-by-field using the matching property names.
The target class just needs fields (or a constructor) matching the input's keys. A record works perfectly.
public record AddBookInput(String title, int pages) {}
@MutationMapping
public Book addBook(@Argument AddBookInput input) {
Book created = bookService.create(input.title(), input.pages());
return created;
}@MutationMapping in Practice
@MutationMapping works exactly like @QueryMapping but resolves fields under the root Mutation type. Use it for operations that change state: create, update, delete.
You can mix simple scalar arguments and input objects freely. Below, an update takes both an ID and an input payload.
@MutationMapping
public Book updateBook(@Argument Long id, @Argument UpdateBookInput input) {
Book existing = bookService.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
existing.setTitle(input.title());
existing.setPages(input.pages());
return bookService.save(existing);
}Whole-Argument-Map Binding with @Arguments
Sometimes you want the complete set of arguments bound to a single object rather than calling @Argument repeatedly. The @Arguments (plural) annotation binds all field arguments onto one target class at once.
This is handy when a query has many filter parameters that map cleanly to a criteria object.
public record BookFilter(String titleContains, Integer minPages, Integer maxPages) {}
@QueryMapping
public List<Book> searchBooks(@Arguments BookFilter filter) {
return bookService.search(filter);
}Validating Bound Arguments
Spring for GraphQL integrates with Bean Validation. Annotate the controller method argument or the input record components with constraints, and add @Valid so violations are checked before your method body runs.
A failed constraint produces a GraphQL error rather than executing your business logic, keeping bad data out of the service layer.
public record AddBookInput(
@NotBlank String title,
@Positive int pages) {}
@MutationMapping
public Book addBook(@Argument @Valid AddBookInput input) {
return bookService.create(input.title(), input.pages());
}Accessing the Raw Arguments Map
For dynamic cases you can skip typed binding and inject the DataFetchingEnvironment (or an @Argument Map<String, Object>). The environment exposes the raw arguments, the selection set, and context.
Use this sparingly — typed binding with @Argument is clearer and safer. Reach for the environment only when you genuinely need engine-level details.
@QueryMapping
public Book book(DataFetchingEnvironment env) {
Long id = Long.valueOf(env.getArgument("id").toString());
return bookService.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
}A Standalone Argument-Coercion Demo
Argument binding is, at its core, coercing incoming values into Java types. The snippet below mimics that idea without any framework: it parses an ID-like string argument into a long and looks it up — exactly what @Argument Long id does under the hood.
This runs on a plain online judge to make the concept concrete.
import java.util.Map;
public class Main {
record Book(long id, String title) {}
public static void main(String[] args) {
Map<Long, Book> store = Map.of(
1L, new Book(1, "Spring in Action"),
2L, new Book(2, "Effective Java")
);
String rawIdArgument = "2"; // as it would arrive from GraphQL
long id = Long.parseLong(rawIdArgument);
Book found = store.get(id);
System.out.println(found != null ? found.title() : "not found");
}
}Quick Check
You have a mutation addBook(input: AddBookInput!): Book! where AddBookInput has fields title and pages. You want to bind the entire input object to a single Java record in one handler. What is the correct signature?
Recap
You can now wire GraphQL fields to Java handlers in Spring for GraphQL:
- @QueryMapping and @MutationMapping bind controller methods to root Query/Mutation fields, inferring the field name from the method name.
- @Argument binds a single GraphQL argument or an entire input object to a Java type; use the explicit name form when parameter names are unavailable.
- @Arguments binds the full set of field arguments onto one target object.
- @Valid plus Bean Validation constraints reject bad input before your service runs.
- The DataFetchingEnvironment exposes raw arguments for dynamic cases, but typed binding should be your default.
คำถามที่พบบ่อย
บทเรียน “ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์”
ใช้งานตัวจัดการ @QueryMapping และ @MutationMapping พร้อมการผูกอาร์กิวเมนต์และอินพุต คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การออกแบบแบบสคีมาเป็นหลักและการแมปชนิด
- ตัวดึงข้อมูลและการผูกอาร์กิวเมนต์
- การแก้ปัญหา N+1 ด้วยตัวโหลดแบบชุด
- การสมัครรับ ข้อผิดพลาด และความปลอดภัยของสคีมา