Spring Boot 4 Complete Guide · درس

التصميم أولًا بالمخطط وتعيين الأنواع

تعريف مخطط GraphQL وتعيين الأنواع والاستعلامات وعمليات التغيير إلى أساليب متحكمات Java.

الدرس 1 من 413 خطوة

التصميم أولًا بالمخطط وتعيين الأنواع درس مجاني في Spring Boot 4 Complete Guide على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Complete Guide، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Complete Guide 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Schema-First in Spring for GraphQL

Spring for GraphQL is schema-first: you describe your API in a .graphql Schema Definition Language (SDL) file, and your Java code maps onto it.

  • The schema is the single source of truth for the API contract.
  • Clients ask for exactly the fields they need.
  • Your controllers provide the data behind each field.

By convention, Spring Boot auto-discovers .graphqls / .graphql files under src/main/resources/graphql/.

Defining Object Types in SDL

A GraphQL object type describes the shape of an entity. Each field has a name and a type.

  • ID, String, Int, Float, Boolean are the built-in scalars.
  • A trailing ! marks a field as non-null.
  • [Type] denotes a list.

Place this in src/main/resources/graphql/schema.graphqls.

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

type Author {
    id: ID!
    name: String!
    books: [Book!]!
}

The Query Root Type

Every read operation lives under the special Query root type. Each field of Query is an entry point a client can call.

  • Fields can take arguments, e.g. bookById(id: ID!).
  • The return type can be a single object, a list, or a scalar.

A nullable return (no !) is appropriate when the entity may not exist.

type Query {
    bookById(id: ID!): Book
    allBooks: [Book!]!
    searchBooks(titleContains: String!): [Book!]!
}

Mapping a Query to a Controller

Spring for GraphQL maps schema fields to Java methods using annotated controllers. A class annotated with @Controller exposes handler methods with @QueryMapping.

  • The method name must match the schema field, or you set @QueryMapping("fieldName").
  • Arguments are bound with @Argument.

This is framework code (it needs the Spring runtime), so it is not standalone-runnable.

@Controller
public class BookController {

    private final BookRepository books;

    public BookController(BookRepository books) {
        this.books = books;
    }

    @QueryMapping
    public Book bookById(@Argument String id) {
        return books.findById(id).orElse(null);
    }

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

Type Mapping: SDL to Java

Spring maps GraphQL types to Java types by field name, not by inheritance. Your POJO (record or class) just needs matching accessors.

  • SDL String → Java String
  • SDL Int → Java int / Integer
  • SDL ID → usually String (or Long coerced)
  • SDL [Book!]! → List<Book>

A Java record is the cleanest representation of a GraphQL object type.

public record Book(
    String id,
    String title,
    Integer pageCount,
    String authorId
) {}

public record Author(
    String id,
    String name
) {}

Argument Binding Details

The @Argument annotation binds a named schema argument to a method parameter.

  • By default the parameter name must match the argument name (requires -parameters compilation, on by default in Spring Boot).
  • Override explicitly with @Argument("titleContains").
  • Complex input types bind to a Java record or class automatically.

Spring coerces the incoming GraphQL value to your parameter's Java type.

@QueryMapping
public List<Book> searchBooks(@Argument("titleContains") String fragment) {
    return books.findAll().stream()
        .filter(b -> b.title().toLowerCase().contains(fragment.toLowerCase()))
        .toList();
}

Resolving Nested Fields with @SchemaMapping

When a field needs extra work beyond a simple getter (e.g. Book.author must be looked up), use @SchemaMapping. The source object is passed as a parameter.

  • The method's class/type is inferred from the parameter type, or set via @SchemaMapping(typeName = "Book").
  • This solves the N+1 concern by letting you batch later with @BatchMapping.

Here, each Book resolves its author field on demand.

@SchemaMapping
public Author author(Book book) {
    return authorRepository.findById(book.authorId())
        .orElseThrow(() -> new IllegalStateException("Author missing"));
}

Defining Mutations in SDL

Write operations live under the Mutation root type. They typically accept an input object and return the created or updated entity.

  • Use a dedicated input type for arguments — input types cannot have fields that reference object types.
  • Returning the mutated entity lets clients re-fetch fresh state in one round trip.
input AddBookInput {
    title: String!
    pageCount: Int
    authorId: ID!
}

type Mutation {
    addBook(input: AddBookInput!): Book!
    deleteBook(id: ID!): Boolean!
}

Mapping a Mutation to a Controller

Mutations map with @MutationMapping. A GraphQL input type binds cleanly to a Java record via @Argument.

  • The record field names must match the SDL input field names.
  • Return the entity to satisfy the non-null Book! result.

Still framework code — needs Spring's GraphQL runtime, so not standalone-runnable.

public record AddBookInput(String title, Integer pageCount, String authorId) {}

@MutationMapping
public Book addBook(@Argument AddBookInput input) {
    Book created = new Book(
        UUID.randomUUID().toString(),
        input.title(),
        input.pageCount(),
        input.authorId()
    );
    return books.save(created);
}

Pure Type Mapping in Plain Java

The data-shaping logic behind a resolver is plain Java — you can reason about it without any server. Below, a search filter (the body of searchBooks) runs as a complete standalone program.

  • This mirrors exactly what your @QueryMapping method does internally.
  • No Spring, no schema engine — just type mapping and filtering.
import java.util.List;

public class Main {
    record Book(String id, String title, Integer pageCount) {}

    static List<Book> searchBooks(List<Book> all, String fragment) {
        return all.stream()
            .filter(b -> b.title().toLowerCase().contains(fragment.toLowerCase()))
            .toList();
    }

    public static void main(String[] args) {
        List<Book> catalog = List.of(
            new Book("1", "Spring in Action", 600),
            new Book("2", "GraphQL Basics", 220),
            new Book("3", "Effective Java", 412)
        );
        searchBooks(catalog, "graphql").forEach(b -> System.out.println(b.title()));
    }
}

Where Schema and Code Meet

At startup Spring validates that every schema field is satisfiable. If a field has no getter and no @SchemaMapping, you may get an unresolved-field error at query time.

  • Properties on your record resolve automatically by name.
  • Computed / fetched fields need an explicit mapping method.
  • Use the GraphiQL UI (enable spring.graphql.graphiql.enabled=true) to explore the live schema.

Keeping SDL and Java field names aligned is the core discipline of schema-first design.

Quick Check

You have a schema field Book.author: Author!, but a Book record only stores authorId and no author property. What is the correct schema-first way to resolve it?

Recap

You mapped a GraphQL schema to Spring controllers, schema-first:

  • SDL files under src/main/resources/graphql/ define object, input, Query, and Mutation types.
  • @QueryMapping handles reads, @MutationMapping handles writes, both binding args with @Argument.
  • @SchemaMapping (and @BatchMapping) resolve nested/computed fields from a source object.
  • Types map by field name: records are the cleanest representation, and SDL scalars map to their natural Java types.

Keep SDL and Java names aligned, and the schema stays the single source of truth.

البدء مجانًا

تعلم Java مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
21
الدروس
84

الأسئلة الشائعة

هل درس «التصميم أولًا بالمخطط وتعيين الأنواع» مجاني؟

نعم — نص درس «التصميم أولًا بالمخطط وتعيين الأنواع» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Complete Guide، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Complete Guide 4 دروس في المجموع.

ماذا ستتعلم في «التصميم أولًا بالمخطط وتعيين الأنواع»؟

تعريف مخطط GraphQL وتعيين الأنواع والاستعلامات وعمليات التغيير إلى أساليب متحكمات Java. تتمرن على Spring Boot 4 Complete Guide مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Complete Guide؟

لا تُشترط خبرة سابقة. Spring Boot 4 Complete Guide على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «التصميم أولًا بالمخطط وتعيين الأنواع»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Complete Guide هذا؟

نعم. كل درس في Spring Boot 4 Complete Guide يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التصميم أولًا بالمخطط وتعيين الأنواع
  2. جالبو البيانات وربط المعلمات
  3. حل مشكلة N+1 باستخدام Batch Loaders
  4. الاشتراكات والأخطاء وأمان المخطط
← العودة إلى Spring Boot 4 Complete Guide