Sub topic 1
Java Records as DTOs in Spring Boot
Prerequisites
This chapter assumes Java 17 or later, basic Java classes, JSON, and a Spring Boot REST controller using @RestController and @PostMapping.
Why API Payloads Need DTOs
A data transfer object (DTO) is a type that defines data crossing an application boundary, such as an HTTP request or response. A persistence entity represents data stored by the database. These roles should usually stay separate.
Returning a JPA entity directly can expose internal fields, database relationships, or fields that clients should not change. It also couples the API format to the database model. A DTO gives the API its own stable contract.
public record UserResponse(Long id, String name, String email) {
}The response contains only the fields that clients need. If the entity later gains a passwordHash or internal audit field, the API does not expose it accidentally.
Records in a Nutshell
A record is a concise Java class for data that is primarily defined by its values. The declaration above creates:
- private final fields named
id,name, andemail - a canonical constructor
- accessors named
id(),name(), andemail() equals,hashCode, andtoString
Records reduce boilerplate, but they do not validate business rules automatically. They also provide shallow immutability: a record cannot replace a field, but a mutable object stored in a field can still change.
How Jackson Reads and Writes Records
Jackson is the JSON library commonly configured by Spring Boot. It writes a record by reading its component accessors. It reads a record by passing JSON values to the canonical constructor.
import com.fasterxml.jackson.databind.ObjectMapper;
record UserResponse(Long id, String name, String email) {
}
class Demo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
UserResponse value = new UserResponse(1L, "Ada", "[email protected]");
String json = mapper.writeValueAsString(value);
UserResponse copy = mapper.readValue(json, UserResponse.class);
System.out.println(json);
System.out.println(copy.name());
}
}This produces JSON such as {"id":1,"name":"Ada","email":"[email protected]"}. Spring Boot configures Jackson for controller request and response bodies, so records normally work without getters or setters.
Exercise
Why should a REST controller usually return a response record instead of a JPA entity?
Show answer
A response record exposes only the intended API fields and prevents the API contract from depending on the persistence model.