Mutações GraphQL: alterando dados
Vá além da leitura de dados: aprenda a definir e implementar mutações GraphQL para criar, atualizar e excluir dados no Spring Boot.
Mutações GraphQL: alterando dados é 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.
From Reading to Writing
You can now define types, resolvers, and run queries. But real APIs must also change data.
In GraphQL, every write goes through a mutation — the counterpart to a query.
Query vs Mutation
The shapes look similar, but intent differs:
- Query: read data, no side effects, may run in parallel.
- Mutation: change data, executed sequentially top to bottom.
Declaring a Mutation in the Schema
Mutations live under the special Mutation type and usually return the affected object.
type Mutation {
createBook(title: String!, author: String!): Book
}Input Types for Complex Arguments
For many fields, group arguments into an input type instead of a long argument list.
input BookInput {
title: String!
author: String!
}
type Mutation {
createBook(book: BookInput!): Book
}Implementing the Resolver
In Spring Boot, annotate the handler with @MutationMapping.
@Controller
class BookMutation {
@MutationMapping
Book createBook(@Argument String title, @Argument String author) {
return new Book(title, author);
}
}Returning the Result
Returning the created or updated object lets the client immediately read back any fields it needs.
mutation {
createBook(title: "Clean Code", author: "Martin") {
id
title
}
}Update and Delete Mutations
The same pattern covers all writes.
type Mutation {
updateBook(id: ID!, book: BookInput!): Book
deleteBook(id: ID!): Boolean
}A Self-Contained Logic Example
The resolver logic is plain Java; here is the core idea as a runnable snippet.
import java.util.*;
public class Main {
static Map<Integer,String> store = new HashMap<>();
static int seq = 0;
static int createBook(String title){ int id = ++seq; store.put(id, title); return id; }
public static void main(String[] a){
int id = createBook("Clean Code");
System.out.println("Created id=" + id + " title=" + store.get(id));
}
}Validating Input
Mutations are the right place to enforce rules: reject empty titles, check permissions, ensure referenced records exist.
Return clear errors so clients can react meaningfully.
Sequential Execution Matters
Unlike query fields, top-level mutation fields run one after another.
This guarantees that if a single request contains several mutations, earlier ones complete before later ones begin — important for consistency.
Best Practices
- Use input types for multi-field arguments.
- Return the affected object so clients can re-read fields.
- Validate and authorize inside resolvers.
- Name mutations as verbs: createBook, updateBook, deleteBook.
Quick Check
Test your understanding of GraphQL mutations.
Recap
You learned to change data with GraphQL mutations.
- Define them under the Mutation type, often with input types.
- Implement with @MutationMapping in Spring Boot.
- They run sequentially and should validate and return the affected object.
Perguntas Frequentes
A aula “Mutações GraphQL: alterando dados” é grátis?
Sim — o texto completo de “Mutações GraphQL: alterando dados” é 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 “Mutações GraphQL: alterando dados”?
Vá além da leitura de dados: aprenda a definir e implementar mutações GraphQL para criar, atualizar e excluir dados 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 “Mutações GraphQL: alterando dados”?
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
- Definindo Tipos de Dados Personalizados
- Implementando Resolvedores de Dados
- Executando Consultas GraphQL Simples
- Mutações GraphQL: alterando dados