0Pricing
GraphQL APIs with Spring Boot · 课时

验证变更输入参数

学习如何在 Spring Boot GraphQL API 中使用 Bean Validation 验证传入的变更参数,确保只有干净且格式正确的数据能够到达数据层。

验证变更输入参数 是 CoddyKit 上的免费 GraphQL APIs with Spring Boot 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 GraphQL APIs with Spring Boot 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 GraphQL APIs with Spring Boot 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Validate Mutation Input?

Mutations change your data, so the arguments they receive must be trustworthy. Without validation, clients could send empty names, negative prices, or malformed emails straight into your database.

Input validation rejects bad data early and returns a clear error before any persistence happens.

Validation in the GraphQL Lifecycle

GraphQL already validates the shape of your input against the schema (types, required fields). But it does not check business rules like 'price must be positive'.

That semantic layer is your responsibility, and Spring's Bean Validation fits perfectly here.

Bean Validation Annotations

Spring Boot ships with Jakarta Bean Validation. Common annotations:

  • @NotNull, @NotBlank for required values
  • @Size for length bounds
  • @Min, @Max, @Positive for numbers
  • @Email for email format

Annotating an Input Class

Map your GraphQL input type to a Java record or class and add constraints to its fields.

public record CreateBookInput(
    @NotBlank String title,
    @Size(min = 2, max = 60) String author,
    @Positive double price
) {}

Triggering Validation in a Resolver

Add @Valid to the argument in your mutation method. Spring then checks every constraint before the method body runs.

@MutationMapping
public Book createBook(@Argument @Valid CreateBookInput input) {
    return bookService.create(input);
}

What Happens on Failure

If a constraint fails, Spring throws a ConstraintViolationException before your service code runs. The mutation does not persist anything, protecting your data layer from invalid state.

Custom Error Messages

Each annotation accepts a message attribute so clients see helpful feedback instead of a generic failure.

@NotBlank(message = "Title is required")
String title;

Mapping Violations to GraphQL Errors

Use a DataFetcherExceptionResolver to turn validation exceptions into clean GraphQL errors with field-level detail, so clients know exactly which input was wrong.

@Override
public GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
    return GraphqlErrorBuilder.newError(env)
        .errorType(ErrorType.BAD_REQUEST)
        .message(ex.getMessage())
        .build();
}

Custom Validators

For rules the built-in annotations cannot express (like 'ISBN must be unique'), write a custom constraint implementing ConstraintValidator and annotate fields with it.

public class IsbnValidator implements ConstraintValidator<ValidIsbn, String> {
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        return value != null && value.matches("\\d{13}");
    }
}

Validating Nested Inputs

When an input contains another object, mark the nested field with @Valid too. Validation then cascades into the child object.

public record OrderInput(
    @NotNull @Valid AddressInput shippingAddress,
    @Positive int quantity
) {}

Best Practices

Keep validation reliable:

  • Validate at the boundary, before any business logic
  • Return field-specific messages clients can act on
  • Reuse input classes across related mutations
  • Keep custom validators stateless and fast

Quick Check

Test your understanding of mutation validation.

Recap

You learned to validate mutation input:

  • GraphQL checks shape; you enforce business rules
  • Annotate input classes with Bean Validation constraints
  • Use @Valid in resolvers to trigger checks
  • Map violations to clean GraphQL errors
  • Write custom validators and cascade with nested @Valid

Validated mutations keep your data layer safe and clean.

常见问题解答

「验证变更输入参数」课时是免费的吗?

是的 — 「验证变更输入参数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 GraphQL APIs with Spring Boot 课程的其余内容,请升级到 CoddyKit PRO。 GraphQL APIs with Spring Boot 课程共包含 4 节课。

「验证变更输入参数」这节课中我会学到什么?

学习如何在 Spring Boot GraphQL API 中使用 Bean Validation 验证传入的变更参数,确保只有干净且格式正确的数据能够到达数据层。 你通过在浏览器中直接运行的动手代码来练习 GraphQL APIs with Spring Boot,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 GraphQL APIs with Spring Boot 需要有经验吗?

无需任何先前经验。CoddyKit 上的 GraphQL APIs with Spring Boot 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「验证变更输入参数」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 GraphQL APIs with Spring Boot 课中编写并运行代码吗?

能。每节 GraphQL APIs with Spring Boot 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 理解 GraphQL 变更
  2. 使用变更创建数据
  3. 更新与删除数据
  4. 验证变更输入参数
← 返回 GraphQL APIs with Spring Boot