Sub topic 8
Validating nested objects and collections
This chapter assumes you can declare constraints on a request DTO, trigger them with @Valid @RequestBody, and handle MethodArgumentNotValidException in a @RestControllerAdvice, as covered earlier in this tutorial. It also assumes you know Java records and generics. Here you will learn why nested objects are skipped by default, how to cascade into them, and how to constrain collection elements.
Why nested objects are not validated by default
Bean Validation checks the constraints declared directly on the object you hand it. It does not look inside the objects that object holds. Consider this DTO:
public record OrderRequest(
@NotBlank String customerId,
Address shippingAddress) {
}Suppose Address has @NotBlank on its street. A request with "street": "" still passes, because nothing tells the validator to descend into shippingAddress. This is a common source of silent gaps: the nested class looks protected, but its constraints never run.
The @Valid annotation turns on cascading. When the validator finds @Valid on a property, it validates the referenced object as well, and repeats the process for that object's own @Valid properties.
Cascading into a nested object
Mark the property with @Valid. For a record, put the annotation on the component.
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
import java.util.List;
public record OrderRequest(
@NotBlank String customerId,
@NotNull @Valid Address shippingAddress,
@NotEmpty @Size(max = 50) List<@NotNull @Valid OrderLine> lines) {
public record Address(
@NotBlank String street,
@NotBlank @Size(min = 2, max = 2) String country) {
}
public record OrderLine(
@NotBlank String sku,
@Positive int quantity) {
}
}Three details in this DTO matter.
@Validskipsnull. IfshippingAddressis missing, noAddressconstraint runs and nothing reports the absence. Pair@Validwith@NotNullwhen the nested object is required.- A nested object's constraints apply only when it is reached through a
@Validpath. The sameAddressrecord used elsewhere without@Validis unchecked there. - Hibernate Validator remembers which objects it has already visited on a path, so a cyclic graph (an order that references a customer that references the order) does not loop forever.
Validating collections
A collection has two kinds of rules: rules about the collection itself (not empty, at most 50 items) and rules about each element. Bean Validation 2.0 and later lets you put constraints on the type argument, which is called a container element constraint.
List<@NotNull @Valid OrderLine> linesRead this as "a list whose elements are each non-null and valid". Constraints placed before List apply to the list; constraints placed inside <...> apply to each element. The two groups are independent:
| Declaration | Meaning |
|---|---|
| `@NotEmpty List<OrderLine> lines` | The list must have at least one element. Elements are not checked. |
| `@Valid List<OrderLine> lines` | Each non-null element is cascaded into. A null list or null element passes. |
| `List<@Valid OrderLine> lines` | Same cascade into elements, written on the type argument. |
| `List<@NotNull @Valid OrderLine> lines` | Elements must be non-null and valid. |
| `List<@NotBlank String> tags` | Each string in the list must not be blank. |
For a List, @Valid on the property and @Valid on the type argument both cascade into the elements, so you only need one. The type-argument form is preferable because it sits next to the element-level constraints such as @NotNull. Writing @Valid in both places adds nothing.
The same syntax works for other containers. Hibernate Validator supports Set, Map (constrain keys and values separately, as in Map<@NotBlank String, @Valid OrderLine>), arrays, and Optional.
Running the validator directly
You can see exactly what the validator reports without starting a web server. This program builds a default validator and prints each violation with its property path. It works in any project that has spring-boot-starter-validation on the classpath, which pulls in Hibernate Validator and the expression language support it needs for message interpolation.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import java.util.List;
import java.util.Set;
public class NestedValidationDemo {
public static void main(String[] args) {
OrderRequest request = new OrderRequest(
"c-1",
new OrderRequest.Address("", "DEU"),
List.of(
new OrderRequest.OrderLine("A1", 2),
new OrderRequest.OrderLine("", 0)));
try (var factory = Validation.buildDefaultValidatorFactory()) {
Validator validator = factory.getValidator();
Set<ConstraintViolation<OrderRequest>> violations = validator.validate(request);
violations.stream()
.map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted()
.forEach(System.out::println);
}
}
}With an English default locale, the output is:
lines[1].quantity: must be greater than 0
lines[1].sku: must not be blank
shippingAddress.country: size must be between 2 and 2
shippingAddress.street: must not be blankThe first line of lines (index 0) is valid and produces nothing. The property path is the useful part. It records where the violation sits in the graph: lines[1].sku means the sku of the element at index 1.
What the client sees
When the request arrives through a controller with @Valid @RequestBody OrderRequest, Spring raises MethodArgumentNotValidException. Its field errors carry the same paths, so the handler from the previous chapter, which maps error.getField() to error.getDefaultMessage(), needs no change. A response looks like this:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"instance": "/orders",
"errors": {
"shippingAddress.street": "must not be blank",
"shippingAddress.country": "size must be between 2 and 2",
"lines[1].sku": "must not be blank",
"lines[1].quantity": "must be greater than 0"
}
}The order of entries in errors is not guaranteed, because the validator does not promise an order for violations. Clients should look errors up by key and not rely on position.
The indexed keys are convenient for a form UI. A front end can match lines[1].sku to the second row of an order table and show the message beside that input.
Common errors
The mistakes below account for most nested-validation bugs.
- Forgetting
@Validon the nested property. The nested constraints are silently ignored. A test that sends an invalid nested object and expects a 400 catches this quickly. - Expecting
@Validto reject null. It does not. Add@NotNullfor required objects and@NotEmptyfor required collections. - Putting a constraint on the wrong side of
<...>.@NotBlank List<String>is invalid because@NotBlankapplies to character sequences, not lists. Hibernate Validator fails at validation time with a "no validator found" error. WriteList<@NotBlank String>instead. - Leaving collections unbounded. Cascading runs the validator once per element. A request with a million lines costs a million validations. Add
@Size(max = ...)on the collection and also limit body size at the server level. - Validating a top-level list body. With
@RequestBody List<OrderLine>, there is no DTO to hold the annotations. Wrapping the list in a request record, asOrderRequestdoes, keeps the rules in one place and the error handling the same as for any other body.
Choosing where to cascade
Cascade through every property the client controls, because those values are untrusted. Skip cascading for objects you build yourself on the server side. Re-checking them wastes time and can produce errors the client cannot fix. For nested types shared between create and update requests, the cleanest approach is usually one small record per concept (Address, OrderLine) with its constraints declared once, and @Valid on each property that uses it.
Exercise
A request DTO declares @NotEmpty List<OrderLine> lines, and OrderLine has @Positive int quantity. A client posts {"customerId":"c-1","lines":[{"sku":"A1","quantity":-5}]} and gets a 201 instead of a 400. What is wrong, and how do you fix it so that a null element is also rejected?
Show answer
Nothing cascades into the elements, because @NotEmpty only checks that the list has elements. Change the declaration to @NotEmpty List<@NotNull @Valid OrderLine> lines. @Valid makes the validator check each element's @Positive, and @NotNull on the type argument rejects a null element, which @Valid would otherwise skip. The error for the example body would then be reported under the path lines[0].quantity.