0Pricing
GraphQL APIs with Spring Boot · Aula

Referências de entidades e a diretiva @key

Domine o núcleo da Apollo Federation: entenda como os subgrafos compartilham entidades usando a diretiva @key e resolvem referências de outros subgrafos no Spring Boot.

Referências de entidades e a diretiva @key é uma aula grátis de GraphQL APIs with Spring Boot no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de GraphQL APIs with Spring Boot, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de GraphQL APIs with Spring Boot inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “Referências de entidades e a diretiva @key” é grátis?

Sim — o texto completo de “Referências de entidades e a diretiva @key” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de GraphQL APIs with Spring Boot, atualize para CoddyKit PRO. O curso de GraphQL APIs with Spring Boot inclui 4 aulas no total.

O que vou aprender em “Referências de entidades e a diretiva @key”?

Domine o núcleo da Apollo Federation: entenda como os subgrafos compartilham entidades usando a diretiva @key e resolvem referências de outros subgrafos no Spring Boot. Você pratica GraphQL APIs with Spring Boot com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar GraphQL APIs with Spring Boot?

Nenhuma experiência prévia é necessária. GraphQL APIs with Spring Boot no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Referências de entidades e a diretiva @key”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de GraphQL APIs with Spring Boot?

Sim. Cada aula de GraphQL APIs with Spring Boot inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Introdução à Federação Apollo
  2. Construindo Subgrafos Federados
  3. Configuração e Gerenciamento do Gateway
  4. Referências de entidades e a diretiva @key
← Voltar para GraphQL APIs with Spring Boot