Video in progress
How do you set an Optional policy across the domain model, REST DTO and JPA entity layers?
Optional only for methods that return a "might not be found" result: repository and service lookups. Entity and DTO fields stay plain nullable, and in the API contract optionality is expressed in the OpenAPI schema. The main goal is that where to expect null is the same across the whole codebase.
📖 Answer
The problem isn't Optional itself but its inconsistent use. One module returns Optional<Customer>, another returns null, and a third puts an Optional in a DTO field and sends {"present": true} out in the JSON.
By layer, this is what I agree on:
| Layer | Rule |
|---|---|
| JPA entity | fields are nullable, no Optional; if needed the getter returns Optional |
| Repository | a single result: Optional<T>; a list: an empty list, never null |
| Domain service | Optional if "not found" is an expected case; otherwise an exception (OrderNotFoundException) |
| REST DTO / record | nullable fields + @Nullable/Bean Validation; no Optional |
| Kafka/JSON schema | optionality in the schema (required), not in code |
The choice between exception and Optional matters too. findById is an Optional, because the caller decides what to do "if it's missing". getById (for example, paying an order) is an exception, because the ID came from outside and its absence is an error, and handling it in every caller is redundant.
In Jackson the jackson-datatype-jdk8 module can serialize Optional, but using it in a DTO makes the API contract vague: null, a missing field and Optional.empty() are three states, and the client doesn't know the difference. If you need the difference between "the field wasn't sent" and "set it to null" in PATCH requests, an explicit type is better for that (JsonNullable or your own Patch<T>).
In the codebase I back this up with Sonar rules and NullAway/JSpecify: if you make a package @NullMarked, the places where null is expected are marked explicitly and the urge to stuff Optional everywhere goes away.
Sign up to mark studied questions and save your progress.