Sub topic 8
Validating nested objects and collections
This chapter assumes you can already put constraint annotations on a request DTO and trigger them with @Valid on a @RequestBody parameter. It covers what happens when the DTO contains other objects or lists of objects.
Why nested constraints are skipped by default
Bean Validation does not look inside a field's value unless you tell it to. Suppose OrderRequest holds a list of OrderLine objects, and each line has its own constraints. Validating the request checks only the constraints declared on OrderRequest. The line constraints are never evaluated, and an invalid line passes.
Adding @Valid to a field marks it for cascading. The validator then descends into that value and checks its constraints too.
Cascading into a list
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;
public record OrderRequest(
@NotBlank String customerId,
@Valid @NotEmpty List<@Valid OrderLine> lines) {
}import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
public record OrderLine(
@NotBlank String sku,
@Positive int quantity) {
}Two kinds of constraint appear on lines:
@NotEmptyapplies to the list itself and rejects a missing or empty list.@Validon the type argument,List<@Valid OrderLine>, applies to each element.
The @Valid on the property is redundant here, because the element-level one already cascades. Many teams write the element form because it is explicit and also works for Map values and Optional.
The controller needs no change. @Valid @RequestBody OrderRequest already starts the cascade.
Reading the error paths
The handler from the previous chapter reports getField() as the key. For nested failures the key is the full property path. A request with a blank SKU in the second line produces this response:
{
"status": 400,
"detail": "Validation failed",
"errors": {
"lines[1].sku": "must not be blank"
}
}The index tells the client which element failed. For a Set, there is no stable position, so the path shows lines[].sku.
Common mistakes
- Missing
@Validon the nested field. This is the most frequent error. The symptom is a 201 response for a request with obviously bad nested data. - Null nested objects.
@Validskipsnullvalues. If the nested object is required, add@NotNullas well. - Constraints on a non-record nested class. Cascading works the same for ordinary classes, but the nested type must itself carry constraint annotations.
@Validon a type with no constraints does nothing. - Applying
@Validto a parameter that is a list. A controller method taking@RequestBody List<OrderLine>is not cascaded by a plain@Valid. Wrap the list in a DTO, or useList<@Valid OrderLine>on the parameter with@Validatedon the class. That route reports failures asConstraintViolationException, notMethodArgumentNotValidException.
Checking the result
Send an order whose first line has quantity 0:
POST /orders
{"customerId":"c-1","lines":[{"sku":"A1","quantity":0}]}The response is a 400 with the key lines[0].quantity and the message must be greater than 0. Removing @Valid from both places makes the same request succeed, which shows that the cascade is what runs the line constraints.
Exercise
An OrderRequest has @NotEmpty List<OrderLine> lines, with no @Valid anywhere. A client sends one line with a blank sku. Does the request return 400, and what two changes would make nested errors appear with paths like lines[0].sku?
Show answer
It does not return 400 for the blank sku. @NotEmpty passes because the list has one element, and the OrderLine constraints are never evaluated. To fix it, add @Valid to the element type (List<@Valid OrderLine>) or to the property, and make sure OrderLine declares @NotBlank on sku. If a line can be null, add @NotNull to the element as well. The existing handler then reports the key lines[0].sku.