Sub topic 11
Using validation groups for create and update
This chapter assumes you can write a Spring MVC controller, declare constraints on a record, and trigger validation with @Valid. It also assumes you know how MethodArgumentNotValidException is handled in a @RestControllerAdvice. If any of that is unfamiliar, review the earlier chapters first.
Why one set of rules is not enough
A create request and an update request often share a DTO (data transfer object) but not the same rules. On create, the client must not send an id, because the server assigns it. On update, the id is required. A password may be mandatory on create and optional on a profile update. If you annotate one DTO with plain constraints, every rule applies to every operation, and one of the two operations will be wrong.
You have three ways to handle this:
- Write one DTO per operation, such as
CreateUserRequestandUpdateUserRequest. - Use validation groups on one shared DTO.
- Validate in the service layer with code.
Separate DTOs are the simplest and are usually the best default. Groups are worth the extra complexity when the two shapes are almost identical and duplicating them would cause drift. This chapter covers groups.
What a validation group is
A validation group is a marker type, normally an empty interface. Each constraint annotation has a groups attribute that lists the groups the constraint belongs to. When you validate, you name the groups to run. Only constraints that belong to a requested group are checked.
If a constraint does not declare groups, it belongs to the built-in group jakarta.validation.groups.Default. A plain @Valid or a plain call to Validator.validate(obj) runs only the Default group.
Define one marker interface per operation:
package com.example.users.validation;
public interface OnCreate {
}package com.example.users.validation;
public interface OnUpdate {
}Assigning constraints to groups
Put the group types in each constraint's groups attribute. A constraint can belong to several groups.
package com.example.users;
import com.example.users.validation.OnCreate;
import com.example.users.validation.OnUpdate;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Null;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record UserRequest(
@Null(groups = OnCreate.class, message = "id must not be sent on create")
@NotNull(groups = OnUpdate.class, message = "id is required on update")
Long id,
@NotBlank(groups = {OnCreate.class, OnUpdate.class})
@Size(max = 50, groups = {OnCreate.class, OnUpdate.class})
String name,
@NotBlank(groups = OnCreate.class)
@Email(groups = {OnCreate.class, OnUpdate.class})
String email) {
}Here the rules differ by operation:
| Field | Create | Update |
|---|---|---|
| `id` | must be null | must not be null |
| `name` | not blank, at most 50 characters | not blank, at most 50 characters |
| `email` | not blank, valid format | valid format if present |
@Email accepts null, so on update an omitted email passes. Most standard constraints treat null as valid, except @NotNull, @NotBlank, and @NotEmpty.
Triggering a group with @Validated
@Valid has no groups attribute, so it cannot select a group. To choose a group for a request body, use Spring's @Validated annotation on the parameter and pass the group types as its value.
package com.example.users;
import com.example.users.validation.OnCreate;
import com.example.users.validation.OnUpdate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public ResponseEntity<Void> create(
@Validated(OnCreate.class) @RequestBody UserRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@PutMapping("/{id}")
public ResponseEntity<Void> update(
@PathVariable long id,
@Validated(OnUpdate.class) @RequestBody UserRequest request) {
return ResponseEntity.noContent().build();
}
}A failure still raises MethodArgumentNotValidException, so the handler you already wrote for @Valid works unchanged.
Note that @Validated on a method parameter is different from @Validated on a class. On a parameter of a @RequestBody argument, Spring MVC's argument resolver reads it and passes the groups to the validator. On a class, it turns on method-level validation through a proxy, which is how path variable constraints work.
The Default group trap
When you request only OnCreate, the Default group does not run. Any constraint with no groups attribute is silently skipped. This is the most common groups bug.
Suppose you add @Size(max = 100) String nickname to the record without a groups value. @Validated(OnCreate.class) will not enforce it, and an oversized nickname passes.
There are two ways to avoid this:
- Always put every constraint in an explicit group. This is predictable but verbose.
- Make the group interfaces extend
Default, so that requesting a group also runs the ungrouped constraints.
The second option looks like this:
package com.example.users.validation;
import jakarta.validation.groups.Default;
public interface OnCreate extends Default {
}package com.example.users.validation;
import jakarta.validation.groups.Default;
public interface OnUpdate extends Default {
}With this change, validating OnCreate also validates every constraint in Default. Ungrouped constraints such as nickname now apply to both operations. Group inheritance works the same way for any interface: validating a group also validates every group it extends.
There is a side effect to check. A constraint declared with groups = OnCreate.class runs on create only, but a constraint with no groups runs in both. That is usually what you want, as long as you know it.
Group inheritance and shared rules
You can build a hierarchy to avoid listing several groups on every constraint. Define a shared group for rules common to both operations and let each operation extend it.
package com.example.users.validation;
public interface Common {
}package com.example.users.validation;
public interface OnCreate extends Common {
}With this layout, a constraint declared groups = Common.class runs when you validate OnCreate or OnUpdate, provided both extend Common. This replaces groups = {OnCreate.class, OnUpdate.class} with a single name. Keep the hierarchy shallow. Deep trees make it hard to tell which rules run for a request.
Group sequences: controlling order
By default, Bean Validation checks all constraints of the requested groups and reports every failure. Sometimes you want cheap checks to run first, and expensive checks to run only if the cheap ones pass. A group sequence defines that order. Validation stops at the first group in the sequence that produces a violation.
package com.example.users.validation;
import jakarta.validation.GroupSequence;
import jakarta.validation.groups.Default;
public interface Expensive {
}
@GroupSequence({Default.class, Expensive.class})
public interface Ordered {
}Because Java allows only one public top-level type per file, put Ordered in its own file when you use this. With @Validated(Ordered.class), the Default constraints run first. The Expensive group runs only if none of them failed. A typical use is putting a database uniqueness check in Expensive so it is not called for a request that already has an empty name.
Seeing the difference
Send a create request that includes an id:
{"id": 7, "name": "Ada", "email": "[email protected]"}POST /users fails with status 400, because @Null(groups = OnCreate.class) rejects the id. The same body sent with PUT /users/7 passes the id rule. Send {"name": "Ada"} to PUT /users/7 and the response is 400 for the missing id, while the missing email is accepted.
Common errors
| Symptom | Likely cause |
|---|---|
| A constraint never fires | It has no `groups` and the requested group does not extend `Default` |
| Every rule fires on both operations | The controller uses `@Valid`, which runs only `Default`, and the constraints have no groups |
| Nothing is validated at all | The parameter lacks both `@Valid` and `@Validated` |
| Compile error on `groups` | The value is not a `Class<?>`; pass `OnCreate.class`, not a string |
| Update passes with missing fields | The field's constraint is in `OnCreate` only |
Also remember that groups apply to nested objects only if the nested field is cascaded with @Valid. The requested groups are passed down to the nested object, so its constraints need matching groups as well.
Testing groups with a plain Validator
You can test group behavior without starting Spring by building a Validator directly. This is fast and isolates the rules.
package com.example.users;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.example.users.validation.OnCreate;
import com.example.users.validation.OnUpdate;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class UserRequestGroupsTest {
private static ValidatorFactory factory;
private static Validator validator;
@BeforeAll
static void setUp() {
factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@AfterAll
static void tearDown() {
factory.close();
}
@Test
void createRejectsAnId() {
UserRequest request = new UserRequest(7L, "Ada", "[email protected]");
assertFalse(validator.validate(request, OnCreate.class).isEmpty());
}
@Test
void updateRequiresAnId() {
UserRequest request = new UserRequest(null, "Ada", null);
assertFalse(validator.validate(request, OnUpdate.class).isEmpty());
}
@Test
void updateAllowsMissingEmail() {
UserRequest request = new UserRequest(7L, "Ada", null);
assertTrue(validator.validate(request, OnUpdate.class).isEmpty());
}
}This test needs the spring-boot-starter-validation dependency on the test classpath, which is already present from the earlier chapters. The same validate(object, groups...) method accepts several groups at once.
Choosing between groups and separate DTOs
| Criterion | Groups | Separate DTOs |
|---|---|---|
| Duplication | One class | Two classes with repeated fields |
| Clarity of the API contract | Weaker, since one class has fields that apply to only some operations | Stronger, since each class matches one endpoint |
| Risk of silent mistakes | Higher (the `Default` trap) | Lower |
| OpenAPI documentation | Shows one schema for both operations | Shows one accurate schema per operation |
| Fit for many operations | Gets cluttered quickly | Scales well |
Use groups when two operations differ by one or two rules. Switch to separate DTOs when the field sets or rules diverge much.
Exercise
A controller method is declared as create(@Validated(OnCreate.class) @RequestBody UserRequest request). The record has @Size(max = 100) String nickname with no groups attribute, and OnCreate is a plain interface that does not extend anything. A client sends a 300-character nickname. Does the request pass validation, and how do you make the nickname rule apply?
Show answer
The request passes. Only the OnCreate group runs, and the nickname constraint belongs to Default, which is not requested. To fix it, either add groups = OnCreate.class to the @Size annotation, or make OnCreate extend jakarta.validation.groups.Default so that ungrouped constraints run with it.
Exercise
Why can you not select a validation group with @Valid, and what do you use instead on a @RequestBody parameter?
Show answer
@Valid is a standard Jakarta annotation with no attribute for groups, so it always runs the Default group. Use Spring's org.springframework.validation.annotation.Validated on the parameter and pass the group classes, for example @Validated(OnUpdate.class).