Sub topic 9
Shallow immutability and what records cannot do
This chapter assumes you can write a Spring Boot REST controller, you know basic record syntax, and you have seen compact canonical constructors. It covers where records stop helping, so you can choose them for the right jobs.
What immutable means for a record
The fields of a record are private final. After construction, no code can point a component at a different object. That is the whole guarantee. It is called shallow immutability: the record's references are fixed, but the objects they refer to may still change.
import java.util.ArrayList;
import java.util.List;
public record OrderRequest(String customerId, List<String> itemIds) {
}
class ShallowDemo {
public static void main(String[] args) {
List<String> items = new ArrayList<>(List.of("a", "b"));
OrderRequest request = new OrderRequest("c-1", items);
items.add("c"); // the caller changes its own list
request.itemIds().add("d"); // the accessor hands out the same list
System.out.println(request.itemIds()); // [a, b, c, d]
}
}The record never changed which list it holds. The list itself changed twice. For a DTO this matters: a service that trusts the payload may see different data from the data that passed validation.
Defensive copies in the compact constructor
Fix the problem where the record is built. Copy mutable inputs in the compact canonical constructor.
import java.util.List;
public record OrderRequest(String customerId, List<String> itemIds) {
public OrderRequest {
itemIds = List.copyOf(itemIds);
}
}List.copyOf returns an unmodifiable list. If the caller later changes the original list, the record is unaffected. Calling add on itemIds() now throws UnsupportedOperationException. List.copyOf also throws NullPointerException for a null list and for null elements. Jackson will surface that as a failed deserialization, which usually becomes a 400 response. If a missing list is acceptable, handle null first:
public OrderRequest {
itemIds = itemIds == null ? List.of() : List.copyOf(itemIds);
}Copying is shallow too. If the list holds mutable objects, those objects can still change. Prefer elements that are strings, numbers, or other records.
Arrays are the worst case. A record with an array component exposes the array through its accessor, and equals compares arrays by identity. Use a List instead.
What records cannot do
| Limit | Consequence |
|---|---|
| Cannot be JPA entities | JPA needs a no-argument constructor, non-final fields, and the ability to create proxies. Records have none of these. |
| Cannot extend a class | A record implicitly extends `java.lang.Record`. It can implement interfaces. |
| Cannot declare instance fields | Only the components are instance state. Static fields are allowed. |
| Cannot be subclassed | Records are implicitly `final`. |
| Cannot be partly filled in | Every component must be passed to the canonical constructor. |
| Not a good fit for partial updates | A missing JSON property and an explicit null both arrive as `null`. |
The first row is the one that shapes a Spring application. Keep User as a normal class with @Entity, and use records only at the boundary. That is the reason UserResponse.from(User) exists in this tutorial.
The last row catches teams building PATCH endpoints. With a record such as UpdateUserRequest(String name, String email), you cannot tell "leave name alone" from "set name to null". Options include a wrapper such as Optional or a dedicated patch type, or a JSON Merge Patch library. Choose one deliberately instead of assuming null means "unchanged".
Other gotchas
- Default values. A missing JSON property for a primitive component such as
int agebecomes0, which can slip past a check you meant to catch. UseIntegerwith@NotNullwhen absence must be an error. - Validation is not construction. A compact constructor runs for every instance, including in tests and mapping code. Bean Validation annotations run only when something calls the validator, such as
@Valid. Use the constructor for invariants that must always hold, and annotations for request checks that produce a field-level error response. - Exceptions from constructors. An exception thrown during Jackson binding is reported as an unreadable message, not as a list of field errors. Keep constructor checks for true invariants.
- Lazy loading. Do not store an entity or a lazy collection in a record. Copy plain values out while the persistence session is still open.
Choosing between a record and a class
Use a record when the type is a fixed bundle of values with no identity or behavior beyond reading them. Request bodies, response bodies, and query projections fit this. Use a regular class when you need inheritance, a no-argument constructor for a framework, mutable state, or lazy proxies. JPA entities fall in that group.
Exercise
A teammate declares public record TagsRequest(List<String> tags) {} and says it is immutable because records are immutable. What can go wrong, and how do you fix it?
Show answer
Records are only shallowly immutable. The record always refers to the same list, but a caller who kept a reference to the original list, or any code that calls tags(), can still modify it if it is a mutable list. Add a compact canonical constructor that copies it: public TagsRequest { tags = List.copyOf(tags); }. Handle null first if a missing list is allowed.
Exercise
Why can a record not be used as a JPA entity, and where should records appear in a Spring Boot application instead?
Show answer
JPA needs a no-argument constructor, non-final fields it can set, and the ability to proxy the class. Records have final fields, a canonical constructor and are final classes. Use records at the API boundary as request and response DTOs, and as Spring Data projections, while entities stay ordinary classes.