0Pricing
GraphQL APIs with Spring Boot · บทเรียน

การสร้างข้อมูลด้วยมิวเทชัน

นำมิวเทชันมาใช้ใน Spring Boot เพื่อเพิ่มระเบียนใหม่ลงในแหล่งจัดเก็บข้อมูลส่วนหลังของคุณ

การสร้างข้อมูลด้วยมิวเทชัน เป็นบทเรียน GraphQL APIs with Spring Boot ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน GraphQL APIs with Spring Boot และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส GraphQL APIs with Spring Boot มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro: Adding New Data

GraphQL isn't just for fetching data. It also allows us to change it! Today, we'll learn how to add brand new records to our system using mutations.

This is a core skill for building any interactive application.

Mutation's Role in Creation

In GraphQL, any operation that modifies data on the server is called a Mutation. This includes:

  • Creating new items (our focus today!)
  • Updating existing items
  • Deleting items

Think of queries for reading data and mutations for writing/changing data.

Designing Input Types

When creating data, you often need to provide several fields (e.g., a book's title, author, year). Instead of listing each field as a separate argument for your mutation, we use Input Types.

Input types are special object types used as arguments. They make your schema cleaner and arguments easier to manage, especially for complex objects.

Schema: The createBook Mutation

First, let's define our BookInput and the createBook mutation in our GraphQL Schema Definition Language (SDL).

This tells clients exactly what data is needed to create a book and what the mutation will return.

input BookInput {
  title: String!
  author: String!
  publicationYear: Int
}

type Mutation {
  createBook(book: BookInput!): Book!
}

type Book {
  id: ID!
  title: String!
  author: String!
  publicationYear: Int
}

The Book Data Model

In our Spring Boot application, we'll represent a book using a simple Java class (a Plain Old Java Object, or POJO). This class will hold the data for each book we create.

class Book {
  String id;
  String title;
  String author;
  Integer publicationYear;

  public Book(String id, String title, String author, Integer year) {
    this.id = id;
    this.title = title;
    this.author = author;
    this.publicationYear = year;
  }

  // Getters for all fields (omitted for brevity in snippets)
  public String getId() { return id; }
  public String getTitle() { return title; }
  public String getAuthor() { return author; }
  public Integer getPublicationYear() { return publicationYear; }
}

Simulating Data Storage

For this lesson, we'll keep things simple and store our books in an in-memory list. In a real Spring Boot application, this would typically involve a database (like H2, PostgreSQL, etc.) and a Spring Data JPA repository.

We'll use a static List to simulate our data store for now.

import java.util.ArrayList;
import java.util.List;

public class BookDataStore {
  private static final List<Book> books = new ArrayList<>();

  public static void addBook(Book book) {
    books.add(book);
  }

  public static List<Book> getAllBooks() {
    return new ArrayList<>(books); // Return a copy
  }
}

Implementing the Resolver Method

Now, let's write the Java method that acts as our resolver for the createBook mutation.

This method will receive the BookInput and perform the logic to create a new Book object.

import java.util.UUID; // For generating unique IDs

// Simplified BookInput class for demonstration
class BookInput {
  String title;
  String author;
  Integer publicationYear;

  // Getters (omitted for brevity)
  public String getTitle() { return title; }
  public String getAuthor() { return author; }
  public Integer getPublicationYear() { return publicationYear; }
}

public class BookService {
  public Book createBook(BookInput bookInput) {
    // ... logic to create and save book ...
    return null; // Placeholder
  }
}

Resolver Logic: Adding Data

Here's the detailed logic inside our createBook resolver method. It handles generating an ID, creating the object, and saving it.

import java.util.UUID;

// (Book, BookInput, BookDataStore classes would be available)

public class BookService {
  public Book createBook(BookInput bookInput) {
    // 1. Generate a unique ID for the new book
    String newId = UUID.randomUUID().toString();

    // 2. Create a new Book instance from the input
    Book newBook = new Book(
        newId,
        bookInput.getTitle(),
        bookInput.getAuthor(),
        bookInput.getPublicationYear()
    );

    // 3. Add the new Book to our data store
    BookDataStore.addBook(newBook);

    // 4. Return the newly created Book
    return newBook;
  }
}

Runnable Example: createBook

Here's a simplified runnable example demonstrating how the createBook logic works within a main method. Run it and check the output!

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

// Simplified Book class for runnable snippet
class Book {
  String id;
  String title;
  String author;
  Integer publicationYear;

  public Book(String id, String title, String author, Integer year) {
    this.id = id;
    this.title = title;
    this.author = author;
    this.publicationYear = year;
  }
  public String toString() {
    return "Book{id='" + id.substring(0,4) + "...', title='" + title + "'}";
  }
}

// Simplified BookInput class
class BookInput {
  String title;
  String author;
  Integer publicationYear;

  public BookInput(String title, String author, Integer year) {
    this.title = title;
    this.author = author;
    this.publicationYear = year;
  }
  public String getTitle() { return title; }
  public String getAuthor() { return author; }
  public Integer getPublicationYear() { return publicationYear; }
}

// Simplified DataStore
class SimpleBookDataStore {
  private static final List<Book> books = new ArrayList<>();
  public static void addBook(Book book) { books.add(book); }
  public static List<Book> getAllBooks() { return new ArrayList<>(books); }
}

public class Main {
  public Book createBook(BookInput bookInput) {
    String newId = UUID.randomUUID().toString();
    Book newBook = new Book(
        newId,
        bookInput.getTitle(),
        bookInput.getAuthor(),
        bookInput.getPublicationYear()
    );
    SimpleBookDataStore.addBook(newBook);
    return newBook;
  }

  public static void main(String[] args) {
    Main app = new Main();

    BookInput input1 = new BookInput(
        "The Great Journey", "A. Traveler", 2023
    );
    Book createdBook1 = app.createBook(input1);
    System.out.println("Created: " + createdBook1);

    BookInput input2 = new BookInput(
        "Coding Adventures", "B. Coder", 2024
    );
    Book createdBook2 = app.createBook(input2);
    System.out.println("Created: " + createdBook2);

    System.out.println("\nAll books in store:");
    for (Book b : SimpleBookDataStore.getAllBooks()) {
      System.out.println("- " + b);
    }
  }
}

Quick Check: Mutation Input

Why is using an Input Type generally preferred for mutation arguments compared to individual scalar arguments?

Recap: Creating Data

Great job! You've learned how to implement a GraphQL mutation to create new data records in a Spring Boot context.

  • We defined an Input Type in our schema for cleaner arguments.
  • We created a mutation field (createBook) using this input.
  • We implemented a Java resolver method to handle the creation logic.
  • We saw how to add new data to a simulated store and return the new item.

Next, we'll explore how to update and delete existing data using mutations!

คำถามที่พบบ่อย

บทเรียน “การสร้างข้อมูลด้วยมิวเทชัน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างข้อมูลด้วยมิวเทชัน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส GraphQL APIs with Spring Boot ให้อัปเกรดเป็น CoddyKit PRO คอร์ส GraphQL APIs with Spring Boot มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างข้อมูลด้วยมิวเทชัน”

นำมิวเทชันมาใช้ใน Spring Boot เพื่อเพิ่มระเบียนใหม่ลงในแหล่งจัดเก็บข้อมูลส่วนหลังของคุณ คุณปฏิบัติ GraphQL APIs with Spring Boot ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน GraphQL APIs with Spring Boot หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน GraphQL APIs with Spring Boot บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างข้อมูลด้วยมิวเทชัน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน GraphQL APIs with Spring Boot นี้ได้ไหม

ได้ บทเรียน GraphQL APIs with Spring Boot ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ทำความเข้าใจมิวเทชัน GraphQL
  2. การสร้างข้อมูลด้วยมิวเทชัน
  3. การอัปเดตและลบข้อมูล
  4. การตรวจสอบอาร์กิวเมนต์อินพุตของมิวเทชัน
← กลับไปที่ GraphQL APIs with Spring Boot