Sub topic 2
Records in a nutshell
This chapter assumes you know basic Java classes, have Java 17 or later installed, and have written a Spring Boot @RestController. It covers the record syntax and the members the compiler generates. Later chapters cover JSON binding, validation, and mapping.
What a record is
A record is a class designed to carry immutable data. You list its components in the header, and the compiler generates the rest. Here is a response DTO written as a record:
public record UserResponse(Long id, String name, String email) {
}The equivalent hand-written class needs three private final fields, a constructor, three accessors, equals, hashCode, and toString. The record needs one line.
What the compiler generates
For each component, the compiler generates:
- A private final field.
- A public accessor method with the same name as the component. It is
id(), notgetId(). - A canonical constructor that takes all components in order and assigns them.
equals,hashCode, andtoString, all based on every component.
public class RecordDemo {
record UserResponse(Long id, String name, String email) {
}
public static void main(String[] args) {
UserResponse a = new UserResponse(1L, "Ada", "[email protected]");
UserResponse b = new UserResponse(1L, "Ada", "[email protected]");
System.out.println(a.name());
System.out.println(a.equals(b));
System.out.println(a);
}
}This prints Ada, then true, then UserResponse[id=1, name=Ada, [email protected]]. Two records are equal when all their components are equal. That is value-based equality, which suits data carriers. JPA entities usually need identity-based equality instead.
Rules that shape how you use records
Records have fixed restrictions. These matter once you use them as DTOs.
- A record is implicitly
final. Nothing can extend it. - A record cannot extend another class. It can implement interfaces.
- Fields are final. There are no setters.
- You cannot declare extra instance fields. Only the components are instance state.
- You can add methods, static fields, and static factory methods.
The last point is useful. You can attach a static factory method to a response record. It copies fields from an entity, so the entity never appears in your API:
public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}Chapter "Mapping entities to response records" returns to this pattern in detail.
Annotations on components
You can place annotations on record components. This is how Bean Validation constraints reach a record DTO:
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) {
}Java copies a component annotation to the field, accessor, or constructor parameter, depending on where that annotation is allowed to appear. Validation and Jackson annotations are built to work with this. The Validation chapter covers how to check these constraints.
Common mistakes
- Calling
getName(). Records usename(). Code written for a getter-style bean will not compile. - Expecting setters. You create a new record instead of changing one. If you need to change a value, build a copy with the new value.
- Using a record as a JPA entity. JPA needs a no-argument constructor and mutable fields, which records do not have. Use records for DTOs and projections only.
- Assuming deep immutability. A record's fields cannot be reassigned, but a
Listcomponent can still be mutated if the list itself is mutable. A later chapter covers this.
Check your understanding
Exercise
A record is declared as record Point(int x, int y) {}. You create new Point(1, 2) and call p.getX(). What happens, and what is the correct call?
Show answer
The code does not compile, because records generate accessors named after the component, not getters. The correct call is p.x().
Exercise
Why can a record not be used as a JPA entity, yet work well as a response DTO?
Show answer
JPA entities need a no-argument constructor and mutable fields so the persistence provider can create and update them. Records have final fields and a constructor that takes all components. For a response DTO you only need to build the object once and read from it, which fits a record.