Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

The same CustomerRequest DTO is used for create and partial update. Required-field constraints break PATCH requests, and a cross-field rule (endDate after startDate) is not checked. How would you design validation?

I would usually split the DTO into a create request and a patch request, which is clearer than one class serving two meanings, and use validation groups with @ConvertGroup only when the two really share most rules. The endDate-after-startDate rule needs a class-level custom constraint with a ConstraintValidator that reports the violation on the endDate property path. Rules that need the database, such as uniqueness or allowed state transitions, belong in the service layer, and for JSON Merge Patch or JSON Patch we apply the patch to the current state and validate the result, all reported through one exception mapper.

Why this question is asked

Reusing one DTO for create and update feels efficient until the first PATCH request fails because it did not send a field it did not want to change. At the same time, the most important business rule, that a period ends after it starts, is not checked at all because field-level annotations cannot see two fields. Interviewers ask this scenario because the fix forces a real design decision about where each kind of rule belongs. In this answer, we will reproduce both problems, compare validation groups with separate DTOs, write a class-level constraint, decide what stays out of Bean Validation, show the correct way to validate a patch, and keep errors in one format.

1Reproducing the Two Problems

Here is the shared DTO and the two endpoints that use it.

Java
public record CustomerRequest(
@NotBlank String name,
@NotBlank @Email String email,
@NotNull LocalDate startDate,
@NotNull LocalDate endDate) { }
@POST public Response create(@Valid CustomerRequest r) { ... }
@PATCH @Path("/{id}") public Response patch(@PathParam("id") long id, @Valid CustomerRequest r) { ... }
// PATCH /customers/7 {"email":"new@example.com"}
// -> 400: name must not be blank, startDate must not be null, endDate must not be null
// POST {"name":"Ann","email":"a@example.com","startDate":"2026-12-01","endDate":"2026-01-01"}
// -> 201, although the period ends before it starts

The first problem is a clash of meanings. In a create request, a missing name means the client forgot it; in a partial update, a missing name means do not change it. One set of annotations cannot express both. The second problem is reach: each annotation sees one field, so nothing compares startDate with endDate.

2Option 1: Validation Groups

Bean Validation lets us put constraints into groups, marker interfaces such as Create and Update, and validate only one group at a time. JAX-RS validates in the Default group, so we use @ConvertGroup on the parameter to switch to our group when cascading into the DTO.

Java
public interface Create { }
public interface Update { }
public record CustomerRequest(
@NotBlank(groups = Create.class) @Size(max = 100, groups = {Create.class, Update.class}) String name,
@NotBlank(groups = Create.class) @Email(groups = {Create.class, Update.class}) String email,
@NotNull(groups = Create.class) LocalDate startDate,
@NotNull(groups = Create.class) LocalDate endDate) { }
@POST
public Response create(@Valid @ConvertGroup(to = Create.class) CustomerRequest r) { ... }
@PATCH @Path("/{id}")
public Response patch(@PathParam("id") long id, @Valid @ConvertGroup(to = Update.class) CustomerRequest r) { ... }
// PATCH {"email":"new@example.com"} -> passes: required checks are only in Create
// PATCH {"email":"nope"} -> 400: @Email is in both groups

This works, but every constraint now lists its groups, and a reader must work out each operation's rules in their head. It also leaves an ambiguity: in a PATCH, does null mean do not change, or clear the field? One class cannot tell.

3Option 2: Separate DTOs, Usually Clearer

Two small classes say exactly what each operation accepts. The create request has required fields; the patch request has optional ones and makes the absence explicit.

Java
public record CreateCustomer(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email String email,
@NotNull LocalDate startDate,
@NotNull LocalDate endDate) { }
public record PatchCustomer(
@Size(min = 1, max = 100) String name, // null: unchanged; if present, not empty
@Email String email,
LocalDate startDate,
LocalDate endDate) { }
Groups versus separate DTOs
ConcernValidation groupsSeparate DTOs
Readabilityrules spread across group listseach class shows one operation's rules
Duplicationnonea few repeated annotations
Absent versus null in PATCHcannot tellexplicit, can use Optional or a patch document
API documentationone schema for two meaningsone schema per operation
Good fitoperations that differ in one or two rulescreate versus partial update

Notice @Size(min = 1) on the patch name: a sent name must not be empty, but leaving it out is fine, because most built-in constraints treat null as valid. The cost is a little duplication. Groups suit operations that differ in only one or two rules.

4A Class-Level Constraint for endDate After startDate

A rule involving two fields must be checked on the object, so we write our own constraint annotation that targets the type, and a validator that receives the whole DTO. The trick for good error messages is to attach the violation to the endDate property, so the client sees which field to fix.

Java
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PeriodValidator.class)
public @interface ValidPeriod {
String message() default "must be after startDate";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class PeriodValidator implements ConstraintValidator<ValidPeriod, HasPeriod> {
@Override
public boolean isValid(HasPeriod p, ConstraintValidatorContext ctx) {
if (p == null || p.startDate() == null || p.endDate() == null) return true; // other rules handle nulls
if (p.endDate().isAfter(p.startDate())) return true;
ctx.disableDefaultConstraintViolation();
ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate())
.addPropertyNode("endDate").addConstraintViolation(); // path: endDate
return false;
}
}
@ValidPeriod
public record CreateCustomer(..., LocalDate startDate, LocalDate endDate) implements HasPeriod { }
// POST with startDate 2026-12-01 and endDate 2026-01-01
// -> 400 {"field":"endDate","message":"must be after startDate"}

Returning true for nulls is deliberate: @NotNull already reports missing dates, so the client gets one message per mistake.

5What Stays Out of Bean Validation

Bean Validation checks the shape of the request. It is a poor place for rules that need the database: an email that must be unique, or a status that may only move from ACTIVE to SUSPENDED and never back to PENDING. A ConstraintValidator could query the database, but then validation runs inside or outside a transaction depending on where it is triggered, two concurrent requests can both pass a uniqueness check, and the DTO tests need a database. Those rules belong in the service layer, inside the transaction, backed by database constraints such as a unique index, and reported as domain errors, for example 409 Conflict for a duplicate email or 422 for an illegal state change.

6Validating a Patch: Apply First, Then Validate

With a real patch format, JSON Merge Patch (RFC 7396, media type application/merge-patch+json) or JSON Patch (RFC 6902, application/json-patch+json), the request body is not an object we can validate; it is a description of changes. The rule that matters is whether the result is valid. So we load the current state, apply the patch, map the result to the full model, and validate that with the same rules as create, including the period rule. This catches a patch that sends only an endDate earlier than the stored startDate.

Java
@PATCH @Path("/{id}") @Consumes("application/merge-patch+json")
public CustomerView patch(@PathParam("id") long id, JsonObject patchDoc) {
JsonObject current = toJson(customers.get(id)); // {"name":"Ann",...,"startDate":"2026-03-01"}
JsonValue merged = Json.createMergePatch(patchDoc).apply(current); // JSON-P merge patch
CreateCustomer result = fromJson(merged, CreateCustomer.class);
Set<ConstraintViolation<CreateCustomer>> v = validator.validate(result);
if (!v.isEmpty()) throw new ConstraintViolationException(v); // same mapper, same format
return customers.replace(id, result);
}
// patch {"endDate":"2026-01-01"} with stored startDate 2026-03-01
// -> 400 {"field":"endDate","message":"must be after startDate"}

Throwing ConstraintViolationException ourselves means the same exception mapper formats this error exactly like every other validation error, so clients handle one error shape for all operations.

7Follow-up questions

Why not use Spring's @Validated with groups?

In a Spring MVC controller, @Validated(Create.class) selects groups directly, which is convenient. In JAX-RS there is no such annotation in the standard, so @ConvertGroup is the portable tool. The design argument for separate DTOs applies in both frameworks.

Where should the period rule live if the dates are also changed by a batch job?

The class-level constraint protects the API. If other code paths change the dates, the domain object or the database should enforce it too, for example a CHECK constraint end_date > start_date, so the invariant holds no matter who writes.

8Conclusion

In this answer, we saw why one DTO for create and partial update breaks PATCH requests: a missing field means two different things. Validation groups with @ConvertGroup can separate the rules, but separate create and patch DTOs are usually clearer. The cross-field rule needs a class-level constraint whose validator reports the violation on the endDate path, database-dependent rules such as uniqueness and state transitions belong in the service layer, and for merge patch or JSON patch we apply the patch to the current state and validate the result. One exception mapper keeps every error in the same format.

What to say in the interviewAbout 90 seconds aloud

Open with

The root problem is that one DTO is carrying two meanings: in a create, a missing field is an error, and in a patch, it means leave it unchanged.

Then, if they want more

Validation groups can handle that: I define Create and Update marker interfaces, put the required-field constraints only in Create, and use @Valid with @ConvertGroup on each resource parameter, since JAX-RS validates the Default group.

But I usually prefer separate DTOs, a CreateCustomer with required fields and a PatchCustomer with optional ones, because each class then shows one operation's rules and the API docs show two clear schemas.

For the date rule, field annotations cannot see two fields, so I write a class-level constraint, say ValidPeriod, with a ConstraintValidator that returns true when either date is null, since NotNull handles that, and otherwise reports a violation attached to the endDate property node so the client knows which field to fix.

Rules that need the database, like unique email or allowed status transitions, go into the service layer inside the transaction, backed by database constraints. For a real merge patch, I load the current state, apply the patch, and validate the result with the full rules, which catches a patch that sends only an endDate earlier than the stored start.

And everything goes through one exception mapper, so errors always have the same shape.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "The same CustomerRequest DTO is used for create and partial update. Required-field...": https://scrivio-interview-library.netlify.app/java/jax-rs/41f193e3bb/