Sub topic 2
Records in a nutshell
This chapter covers the Java record feature: what it declares, which members the compiler generates, and the rules that matter when you use records as DTOs (data transfer objects) in Spring Boot. It assumes you know basic Java classes, have Java 17 or later installed, and have written a simple Spring Boot REST controller. Later chapters cover Jackson binding, validation, and mapping in detail. Here we only build the foundation.
What a record is
A record is a special kind of class for carrying immutable data. You list the components (the fields) in the header, and the compiler writes the rest.
public record UserResponse(Long id, String name, String email) {
}That one line replaces a class with three private final fields, a constructor, three accessor methods, equals, hashCode, and toString. Records became a standard feature in Java 16, so any Java 17 project can use them.
Compare the same data written as a traditional class:
import java.util.Objects;
public final class UserResponseClass {
private final Long id;
private final String name;
private final String email;
public UserResponseClass(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserResponseClass other)) return false;
return Objects.equals(id, other.id)
&& Objects.equals(name, other.name)
&& Objects.equals(email, other.email);
}
@Override
public int hashCode() {
return Objects.hash(id, name, email);
}
@Override
public String toString() {
return "UserResponseClass[id=" + id + ", name=" + name + ", email=" + email + "]";
}
}For a DTO, this code adds no information. The record states the same thing in one line, and the compiler guarantees the generated members stay in sync with the components.
What the compiler generates
For a record header record Point(int x, int y), the compiler produces these members.
| Member | What it is |
|---|---|
| `private final int x`, `private final int y` | One private final field per component |
| `Point(int x, int y)` | The canonical constructor, with one parameter per component, in order |
| `int x()`, `int y()` | Accessor methods named after the component, with no `get` prefix |
| `equals(Object)` | True when the other object is the same record type and every component is equal |
| `hashCode()` | A hash computed from all components |
| `toString()` | A string such as `Point[x=1, y=2]` |
The class is also implicitly final, and it extends java.lang.Record. You cannot extend a record, and a record cannot extend another class. A record can implement interfaces.
Here is a small program that shows the generated members at work:
public class RecordDemo {
record UserSummary(Long id, String name) {
}
public static void main(String[] args) {
UserSummary a = new UserSummary(1L, "Ada");
UserSummary b = new UserSummary(1L, "Ada");
System.out.println(a.name()); // Ada
System.out.println(a); // UserSummary[id=1, name=Ada]
System.out.println(a.equals(b)); // true
System.out.println(a == b); // false
System.out.println(a.hashCode() == b.hashCode()); // true
}
}Two records with equal components are equal even though they are different objects. This is value-based equality. It is convenient in tests, because you can compare a whole DTO with one isEqualTo call.
Accessor names
The accessor for component name is name(), not getName(). This matters in two places in a Spring Boot project:
- Your own code calls
created.id(), as the controller in the spec does when it builds theLocationheader. - Libraries that look for JavaBean getters (
getX) do not see record accessors by default. Jackson handles records explicitly, so JSON works. Other tools, such as some template engines or older mapping libraries, may not.
The chapter on Jackson explains how JSON binding works. For now, remember that records are not JavaBeans.
Why records fit DTOs
A DTO carries data across a boundary, for example from an HTTP request into your service. It has no identity and no behavior beyond the data. Records match that role in four ways:
- Immutable by default. Fields are final, and there are no setters. Once a request body is bound, no code can change it by accident.
- No boilerplate. The header is the whole declaration, so the DTO is easy to read and review.
- Value equality. Two DTOs with the same data are equal, which simplifies tests.
- A clear contract. The components are the complete list of fields in the payload.
The previous chapter explained why DTOs should be kept separate from entities. Records are a good way to implement that separation.
Declaring a record
The header lists the components. Annotations on components are allowed, and the next chapters use that to add validation.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@Min(18) int age) {
}You can declare a record as a top-level type in its own file, or nested inside another class or interface. A nested record is implicitly static, so it does not hold a reference to an outer instance. Many projects keep a request and its response together as nested records, but one record per file is easier to navigate in a larger code base.
Adding members to a record
The body of a record can contain more than the generated members:
- Static methods, including factory methods.
- Static fields.
- Instance methods that compute values from the components.
- Additional (non-canonical) constructors, which must delegate to another constructor with
this(...).
It cannot contain extra instance fields. All instance state comes from the header.
The response DTO from the spec uses a static factory method to build itself from an entity:
public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}Here is a record with a derived instance method and a convenience constructor:
public record Money(long amountInCents, String currency) {
public Money(long amountInCents) {
this(amountInCents, "EUR");
}
public double amount() {
return amountInCents / 100.0;
}
}Be careful with derived instance methods on DTOs that Jackson serializes. A method named amount() is not a record component, so Jackson does not treat it as a property. A method named getAmount() could be picked up as a JSON property. Naming matters here, and a later chapter returns to it.
Customizing the canonical constructor
The canonical constructor is the one whose parameters match the header. You can write it in two ways.
Compact form
The compact form has no parameter list. The parameters are implicit, and the fields are assigned automatically at the end. You can reassign the parameters to change what gets stored.
public record CreateUserRequest(String name, String email) {
public CreateUserRequest {
name = name == null ? null : name.strip();
email = email == null ? null : email.strip().toLowerCase();
}
}Inside the compact constructor you assign to the parameter name, not to this.name. Assigning to this.name in a compact constructor is a compile error. The next chapters cover this form in depth, including validation and defensive copies.
Explicit canonical form
The long form lists the parameters and assigns every field yourself:
public record Range(int low, int high) {
public Range(int low, int high) {
if (low > high) {
throw new IllegalArgumentException("low must not exceed high");
}
this.low = low;
this.high = high;
}
}The compact form is shorter and is the better default. Use the explicit form only when you need it.
Two rules apply to an explicit canonical constructor. It must be at least as accessible as the record itself, and it must assign every field.
Records and Spring Boot
Spring Boot 3 requires Java 17, so records work throughout the web layer. Three points are worth knowing from the start.
- Request bodies. Spring MVC passes the JSON body to Jackson, which calls the canonical constructor. A record parameter annotated with
@RequestBodytherefore works without any extra setup. - Validation. Constraint annotations on components are applied when the controller parameter is marked
@Valid. - Immutability helps. Because a bound request cannot change, a validated request stays valid while it moves through your service code.
The controller from the spec shows both DTO roles at once:
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
class UserController {
private final UserService service;
UserController(UserService service) {
this.service = service;
}
@PostMapping
ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
UserResponse created = service.create(request);
return ResponseEntity.created(URI.create("/users/" + created.id())).body(created);
}
}The request record comes in, the response record goes out, and the entity stays hidden inside the service.
What records cannot do
Records have limits. This chapter lists them briefly, and a later chapter treats them in depth.
- They cannot be JPA entities. JPA needs a no-argument constructor and mutable, non-final fields so the provider can create and update instances. Records have final fields and no such constructor. Use ordinary classes for entities and records for DTOs.
- Immutability is shallow. The fields cannot be reassigned, but an object a field points to can still change. A
Listcomponent that holds anArrayListcan be modified through the original reference. - No inheritance. A record cannot extend a class, and no class can extend a record.
- No extra instance fields. Every piece of state must appear in the header.
The shallow immutability point is the one that catches people. Here is an example:
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("c1", items);
items.add("c");
System.out.println(request.itemIds()); // [a, b, c]
}
}The record did not change its field, but the list behind the field changed. A compact constructor with List.copyOf closes this gap:
import java.util.List;
public record OrderRequest(String customerId, List<String> itemIds) {
public OrderRequest {
itemIds = List.copyOf(itemIds);
}
}List.copyOf returns an unmodifiable copy. It also throws NullPointerException if itemIds is null, so decide whether null is a valid value before you add it.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot assign a value to final variable name` in a compact constructor | You wrote `this.name = ...` | Assign to the parameter: `name = ...` |
| Call to `user.getName()` on a record does not compile | Record accessors have no `get` prefix | Call `user.name()` |
| `record cannot extend` compile error | Records cannot extend classes | Implement an interface instead |
| Entity annotated with `@Entity` fails at startup | JPA cannot instantiate or update a record | Make the entity a normal class and map to a record DTO |
| A "unmodifiable" DTO still changes | A mutable collection was stored by reference | Copy it in the compact constructor with `List.copyOf` |
| A template engine does not find a property | The tool expects `getX()` accessors | Call the accessor method directly, or expose a `getX()` method |
Summary of the model
- A record header declares components. The compiler generates fields, a canonical constructor, accessors,
equals,hashCode, andtoString. - Accessors are named after the components, such as
name(). - The compact canonical constructor lets you normalize or check values before the fields are set.
- Records are shallowly immutable, cannot extend classes, and cannot serve as JPA entities.
- These properties make records a natural fit for request and response DTOs.
Exercise
A teammate writes this record, and a caller passes in a mutable ArrayList for tags. Later the caller adds an element to that list. Does the record's tags() change? Rewrite the record so the answer is no.
public record Article(String title, List<String> tags) {
}
Show answer
Yes, tags() changes. Record fields are final, so the reference cannot be reassigned, but the ArrayList it points to is still mutable and shared with the caller. Copy the list in a compact constructor:
public record Article(String title, List<String> tags) {
public Article {
tags = List.copyOf(tags);
}
}
List.copyOf returns an unmodifiable copy that the caller cannot affect. It throws NullPointerException when tags is null.
Exercise
You have a JPA class Product with getId(), getName(), and getPrice() (a BigDecimal). Write a response record ProductResponse with a static factory method from(Product product). Then state how you would read the name from a ProductResponse variable called response.
Show answer
public record ProductResponse(Long id, String name, BigDecimal price) {
public static ProductResponse from(Product product) {
return new ProductResponse(product.getId(), product.getName(), product.getPrice());
}
}
Read the name with response.name(). Record accessors use the component name and have no get prefix.
Exercise
Why can't you declare @Entity public record Customer(Long id, String name) {} and use it with JPA?
Show answer
JPA providers need to create instances through a no-argument constructor and to set field values after loading or when updating. A record has final fields and only the canonical constructor, so the provider cannot do either. Use a normal class for the entity and a record for the DTO.