0Pricing
GraphQL APIs with Spring Boot · Урок

Ссылки на сущности и директива @key

Освойте основу Apollo Federation: узнайте, как подграфы совместно используют сущности с помощью директивы @key и разрешают ссылки на сущности из других подграфов в Spring Boot.

«Ссылки на сущности и директива @key» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Entities Span Subgraphs

In federation, a single type like Product can be owned and extended by several subgraphs. The mechanism that lets them agree on the same object is the entity.

What Makes an Entity

An entity is a type with a @key directive. The key names the field(s) that uniquely identify an instance across subgraphs, like a primary key in a database.

type Product @key(fields: "id") {
  id: ID!
  name: String!
}

The Owning Subgraph

The subgraph that defines a type's core fields is its owner. It is responsible for fetching a full entity given just its key, so the gateway can stitch data together.

Extending an Entity Elsewhere

Another subgraph can add fields to the same entity. It declares the type with the matching @key and marks borrowed fields as external context.

type Product @key(fields: "id") {
  id: ID!
  reviews: [Review!]!
}

The Reference Resolver

When the gateway needs an entity from a subgraph, it calls a special reference resolver, passing only the key fields. The subgraph returns the matching object.

Resolving References in Spring

Spring for GraphQL Federation provides @EntityMapping to implement the reference resolver. The key fields arrive as arguments.

@EntityMapping
public Product product(@Argument String id) {
    return productService.findById(id);
}

Adding the Federation Library

Enable federation by adding the Apollo federation JVM support, which generates the _entities and _service fields the gateway requires.

// build.gradle
implementation 'com.apollographql.federation:federation-graphql-java-support'

Compound Keys

An entity can be identified by multiple fields. List them space-separated in the @key, useful when no single field is unique.

type OrderItem @key(fields: "orderId sku") {
  orderId: ID!
  sku: String!
}

Multiple Keys

A type can declare several @key directives, letting different subgraphs reference it by whichever identifier they hold.

type User @key(fields: "id") @key(fields: "email") {
  id: ID!
  email: String!
}

How the Gateway Stitches Data

The gateway queries the owning subgraph, then sends the entity's keys to other subgraphs via _entities to fetch their extra fields, merging everything into one response.

Best Practices

Design entities carefully:

  • Pick stable, unique key fields
  • One subgraph owns the core fields
  • Keep reference resolvers fast (consider DataLoaders)
  • Use compound keys only when necessary

Quick Check

Test your federation entity knowledge.

Recap

You learned federated entities:

  • An entity is a type with a @key
  • One subgraph owns it; others extend it
  • Reference resolvers (@EntityMapping) fetch by key
  • Compound and multiple keys handle complex identity

Entities and @key are how federation stitches a unified graph from many subgraphs.

Часто задаваемые вопросы

Урок «Ссылки на сущности и директива @key» бесплатный?

Да — полный текст урока «Ссылки на сущности и директива @key» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Чему я научусь в уроке «Ссылки на сущности и директива @key»?

Освойте основу Apollo Federation: узнайте, как подграфы совместно используют сущности с помощью директивы @key и разрешают ссылки на сущности из других подграфов в Spring Boot. Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?

Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Ссылки на сущности и директива @key»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?

Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Знакомство с федерацией Apollo
  2. Создание федеративных подграфов
  3. Настройка и управление шлюзом
  4. Ссылки на сущности и директива @key
← Назад к GraphQL APIs with Spring Boot