Sub topic 9
Shallow immutability and what records cannot do
This chapter assumes you can write a Spring Boot controller, that you have read the earlier chapters on record syntax and compact constructors, and that you run Java 17 or later. Records are a good fit for DTOs, but they guarantee less than many developers assume, and they cannot replace every class in your application. Knowing where those limits lie helps you avoid bugs that look like "my record changed by itself."
What a record actually guarantees
A record declaration gives you three things the compiler enforces:
- The class is implicitly
final, so nobody can subclass it. - Every field generated from a record component is
private final. - There are no setters, so the only way to set state is the canonical constructor.
This means you cannot reassign a component after construction. It does not mean the object graph behind each component is frozen. A final field holds a reference, and final stops you from pointing the field at a different object. It does not stop anyone from changing the object it already points to. This property is called shallow immutability.
Seeing the leak
The record below stores a list without copying it. Two separate paths can then change its contents.
import java.util.ArrayList;
import java.util.List;
public class ShallowDemo {
record OrderRequest(String customerId, List<String> itemIds) {
}
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"); // caller still holds the same list
request.itemIds().add("d"); // the accessor returns the same list
System.out.println(request);
}
}This prints OrderRequest[customerId=c-1, itemIds=[a, b, c, d]]. The record has no setter, yet its state changed twice.
For a DTO this matters in practice. Jackson builds the list, so you might think nobody else holds a reference. But a service that receives the record can pass the list to another component, and that component can sort it, clear it, or add to it. The equals and hashCode of the record change with it. If you use the record as a map key or cache key, the entry can become unreachable.
Defensive copies in the compact constructor
The fix is to copy mutable components on the way in. A compact constructor is the right place, because it runs for every construction path, including Jackson's.
import java.util.List;
public record OrderRequest(String customerId, List<String> itemIds) {
public OrderRequest {
itemIds = itemIds == null ? List.of() : List.copyOf(itemIds);
}
}List.copyOf returns an unmodifiable list. Calling request.itemIds().add("d") now throws UnsupportedOperationException, and later changes to the caller's original list do not affect the record. Some details to remember:
List.copyOfthrowsNullPointerExceptionif the list itself isnull, or if any element isnull. The ternary above turns an absent list into an empty one. Decide deliberately whether that is the behavior you want. Rejecting a missing list with a validation error is often better.- If the argument is already an unmodifiable list created by
List.oforList.copyOf, the call returns it without copying, so the cost is small. Set.copyOfandMap.copyOffollow the same rules.Set.copyOfandMap.copyOfalso rejectnullelements, keys, and values.- The copy is still shallow. If the list holds mutable objects, those objects can still change.
Mutable elements inside collections
If a list contains elements of a mutable type, a copy of the list does not protect them. The practical answer is to make the element types immutable too, usually by making them records of immutable components.
import java.util.List;
public record Basket(String owner, List<Line> lines) {
public record Line(String sku, int quantity) {
}
public Basket {
lines = List.copyOf(lines);
}
}A Basket built this way is deeply immutable, because String and int are immutable and Line is a record of those. Immutability is a property of the whole graph, so one mutable type deep in the structure weakens everything above it.
Other mutable types that appear in DTOs
Collections are the most common case, but not the only one.
java.util.DateandCalendarare mutable. PreferInstant,LocalDate, orOffsetDateTime, which are immutable.- A
StringBuilder, aFile's contents, or a mutable POJO from another library can be changed through any reference. - An array component is mutable and also breaks equality, covered next.
If you must accept a mutable type, copy it in the constructor and copy it again in an overridden accessor. An accessor must be public, have the same name and return type as the component, and not declare checked exceptions.
import java.util.Date;
public record Event(String name, Date at) {
public Event {
at = new Date(at.getTime());
}
@Override
public Date at() {
return new Date(at.getTime());
}
}This works, but it is a sign that the component type is wrong. Switching to Instant removes both copies.
Arrays and generated `equals`
The generated equals, hashCode, and toString methods call the equivalent methods on each component. Arrays do not override equals, so two arrays with the same contents are not equal.
import java.util.Arrays;
public class ArrayDemo {
record Scores(int[] values) {
}
public static void main(String[] args) {
Scores a = new Scores(new int[] {1, 2});
Scores b = new Scores(new int[] {1, 2});
System.out.println(a.equals(b)); // false
System.out.println(a); // Scores[values=[I@...]
System.out.println(Arrays.toString(a.values()));
}
}The record compares array references, and toString prints a type tag and identity hash code. Use a List<Integer> for DTO payloads. If you really need an array, override equals, hashCode, and toString with Arrays.equals, Arrays.hashCode, and Arrays.toString, and copy the array in the constructor and accessor.
What records cannot do
Records are restricted classes. The restrictions are what make them concise, but they rule out some designs.
| Restriction | Consequence | What to do instead |
|---|---|---|
| Cannot extend another class (they implicitly extend `java.lang.Record`) | No shared base class for DTOs | Implement interfaces, or compose with a nested record |
| Cannot declare extra instance fields | State is exactly the components | Add derived methods, or add a component |
| Cannot have setters or reassign fields | No in-place update | Create a new record with the changed values |
| Cannot be abstract | No partial implementations | Use a `sealed interface` with record implementations |
| Component list is fixed at declaration | Hard to add optional fields gradually | Add a component and a secondary constructor, or use a builder in a separate class |
| Cannot be a JPA entity | Persistence needs a different class | Map between entity and record |
Records can implement interfaces, declare static fields and static methods, and have instance methods that compute values from the components.
public record Rectangle(int width, int height) implements Comparable<Rectangle> {
public static final Rectangle UNIT = new Rectangle(1, 1);
public Rectangle(int side) {
this(side, side);
}
public int area() {
return width * height;
}
@Override
public int compareTo(Rectangle other) {
return Integer.compare(area(), other.area());
}
// private int cached; // does not compile: records cannot declare instance fields
}A secondary constructor must delegate to the canonical constructor with this(...). This keeps all validation and normalization in one place.
Be careful with extra methods on a DTO. Jackson treats any public no-argument method named like a getter as a property. A record method such as isEmpty() or getTotal() can therefore add an unexpected field to your JSON output. Use @JsonIgnore on such a method, or name it so it does not look like a getter, for example total(). Plain accessor-style names like area() do not match the getter pattern, but the record's own components are still serialized.
Why a record cannot be a JPA entity
The JPA specification and Hibernate expect an entity to be a mutable, proxyable object. A record fails each requirement:
- The entity needs a no-argument constructor. A record has only constructors that take all components.
- The entity class must not be
final, because the provider creates subclass proxies for lazy loading. A record is always final. - Persistent fields must not be
final, because the provider sets them after creating the instance. Record fields are always final. - The provider tracks changes to an object by comparing its state to a snapshot. An immutable object cannot be changed in a managed session.
This is a design match, not just a technical gap. An entity represents a row with identity and a lifecycle. A record represents a value. Keep your @Entity classes as ordinary classes and use records at the edges, for requests, responses, and projections, as shown in the earlier chapters. Hibernate 6.2 and later can use a record as an @Embeddable value type, which suits small value objects inside an entity. It still does not make the record an entity.
Updates and PATCH semantics
Because records are immutable, "updating" a DTO means building a new one. Java has no built-in "with" syntax, so you write the copy yourself.
public record UserResponse(Long id, String name, String email) {
public UserResponse withName(String newName) {
return new UserResponse(id, newName, email);
}
}This pattern is fine for small records. For records with many components it gets long, which is the point where a builder class or a mapping library earns its place.
A second limit shows up with partial updates. A record such as UpdateUserRequest(String name, String email) cannot distinguish between a JSON body where email is missing and one where email is null. Both produce a null component. If your API needs "leave unchanged" versus "clear this value," a plain record with a nullable type is not enough. Options include a Map<String, Object> body, a wrapper type such as JsonNullable from the jackson-databind-nullable library, or separate endpoints for clearing values. Primitive components have a similar issue: a missing int becomes 0, not "absent." Use Integer when absence must be detectable, and add @NotNull if it is required.
Failure behavior of constructors during binding
The compact constructor runs when Jackson builds the record, before Bean Validation sees the object. If the constructor throws, for example List.copyOf hits a null element, Jackson wraps the exception and Spring MVC reports an unreadable request body, normally as a 400 Bad Request. That response does not come from your @Valid handling and so does not use the same error format as constraint violations. Two consequences follow:
- Keep constructors forgiving about input shape, and let Bean Validation report problems with a consistent response.
- Reserve exceptions in constructors for invariants that must never be broken, no matter how the object is created.
Choosing a design
Use these criteria when you decide how far to go:
- If every component is an immutable type, do nothing extra. The record is deeply immutable.
- If a component is a collection, copy it with
List.copyOf,Set.copyOf, orMap.copyOfin the compact constructor, and make element types immutable. - If a component is a mutable type you do not control, replace it with an immutable type in the DTO, and convert at the mapping step.
- If you need inheritance, shared mutable state, lazy loading, or in-place changes, use a regular class, not a record.
Exercise
A record Team(String name, List<String> members) has no compact constructor. A service calls team.members().clear(). What happens, and how do you prevent it without changing the call site's type?
Show answer
The call succeeds and empties the list, because the record's field is final but the list it references is a mutable object, which is shallow immutability. Add a compact constructor with members = List.copyOf(members);. The accessor then returns an unmodifiable list, and clear() throws UnsupportedOperationException. The constructor also stops later changes to the caller's original list from affecting the record.
Exercise
Give two separate reasons why record Customer(Long id, String name) annotated with @Entity cannot work with Hibernate, and say where you would use a record for the same data.
Show answer
Any two of these: the class is final, so the provider cannot create lazy-loading proxies; it has no no-argument constructor; its fields are final, so the provider cannot set them after instantiation; and an immutable object cannot be tracked and updated as a managed entity. Keep Customer as a regular @Entity class and use a record as the response DTO or as a Spring Data projection, for example record CustomerSummary(Long id, String name).
Exercise
Two Scores(int[] values) records are built from separate arrays containing {1, 2}. Why does equals return false, and what is the simplest fix?
Show answer
The generated equals compares each component with that component's own equals, and arrays use reference equality, so two different array objects are never equal. The simplest fix is to change the component to List<Integer> and copy it with List.copyOf in the compact constructor. Overriding equals, hashCode, and toString with the Arrays helpers also works.