Referencias de entidades y la directiva @key
Domine el núcleo de Apollo Federation: aprenda cómo los subgrafos comparten entidades mediante la directiva @key y resuelven referencias de otros subgrafos en Spring Boot.
Referencias de entidades y la directiva @key es una lección gratuita de GraphQL APIs with Spring Boot en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de GraphQL APIs with Spring Boot, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de GraphQL APIs with Spring Boot incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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.
Preguntas frecuentes
¿La lección «Referencias de entidades y la directiva @key» es gratis?
Sí — el texto completo de «Referencias de entidades y la directiva @key» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de GraphQL APIs with Spring Boot, actualiza a CoddyKit PRO. El curso de GraphQL APIs with Spring Boot incluye 4 lecciones en total.
¿Qué aprenderé en «Referencias de entidades y la directiva @key»?
Domine el núcleo de Apollo Federation: aprenda cómo los subgrafos comparten entidades mediante la directiva @key y resuelven referencias de otros subgrafos en Spring Boot. Practicas GraphQL APIs with Spring Boot con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar GraphQL APIs with Spring Boot?
No se requiere experiencia previa. GraphQL APIs with Spring Boot en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Referencias de entidades y la directiva @key»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de GraphQL APIs with Spring Boot?
Sí. Cada lección de GraphQL APIs with Spring Boot incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción a Apollo Federation
- Construcción de subgrafos federados
- Configuración y gestión del Gateway
- Referencias de entidades y la directiva @key