DTOs & Records
A DTO (Data Transfer Object) is a class whose only job is to carry data across a boundary — here, between your API and its clients. Instead of exposing your JPA entities directly as JSON, you define separate request and response types. Java records make DTOs almost free to write: immutable, compact, with equals, hashCode and toString generated.
Why not return entities?
| Problem when exposing entities | Example |
|---|---|
| leaking internal or sensitive fields | passwordHash, internalNotes appear in JSON |
| mass assignment | a client sends "role":"ADMIN" and it is bound to the entity |
| API breaks when the database changes | renaming a column renames a JSON field |
| lazy-loading surprises | serialising a relationship triggers extra queries or LazyInitializationException |
| infinite recursion | Project.tasks → Task.project → Project.tasks … |
With DTOs, the API contract and the persistence model can evolve independently.
Request and response records
// what clients may send when creating
public record CreateTaskRequest(
@NotBlank @Size(max = 120) String title,
@Size(max = 2000) String description,
@NotNull Priority priority) {}
// what clients may send when updating (all optional = partial update)
public record UpdateTaskRequest(String title, String description, Priority priority, Boolean done) {}
// what clients receive
public record TaskResponse(long id, String title, String description, Priority priority,
boolean done, String projectName) {
public static TaskResponse from(Task task) { // entity -> DTO
return new TaskResponse(task.getId(), task.getTitle(), task.getDescription(),
task.getPriority(), task.isDone(), task.getProject().getName());
}
}The controller only ever sees DTOs:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
TaskResponse create(@Valid @RequestBody CreateTaskRequest req) {
return TaskResponse.from(service.create(req));
}Notice the response flattens the relationship into projectName — the client does not need the whole project object.
Mapping in plain Java
Mapping is just code. Here is a complete, runnable round-trip: request → entity → response, with a partial update that only changes non-null fields:
import java.util.Objects;
enum Priority { LOW, MEDIUM, HIGH }
// the "entity": mutable, has internal fields the API must not expose
class Task {
Long id;
String title;
String description;
Priority priority;
boolean done;
String internalNotes = "created via API";
}
record CreateTaskRequest(String title, String description, Priority priority) {
Task toEntity() {
Task t = new Task();
t.title = title.strip();
t.description = description;
t.priority = priority;
return t;
}
}
record UpdateTaskRequest(String title, String description, Priority priority, Boolean done) {
void applyTo(Task t) {
if (title != null) t.title = title.strip();
if (description != null) t.description = description;
if (priority != null) t.priority = priority;
if (done != null) t.done = done;
}
}
record TaskResponse(long id, String title, String description, Priority priority, boolean done) {
static TaskResponse from(Task t) {
return new TaskResponse(t.id, t.title, t.description, t.priority, t.done);
}
}
class Main {
public static void main(String[] args) {
Task entity = new CreateTaskRequest(" Write tests ", null, Priority.MEDIUM).toEntity();
entity.id = 7L; // assigned by the database
System.out.println("created: " + TaskResponse.from(entity));
new UpdateTaskRequest(null, null, Priority.HIGH, true).applyTo(entity);
TaskResponse after = TaskResponse.from(entity);
System.out.println("patched: " + after);
TaskResponse same = new TaskResponse(7, "Write tests", null, Priority.HIGH, true);
System.out.println("records equal by value: " + after.equals(same));
System.out.println("hash codes equal: " + (Objects.hash(after) == Objects.hash(same)));
}
}created: TaskResponse[id=7, title=Write tests, description=null, priority=MEDIUM, done=false]
patched: TaskResponse[id=7, title=Write tests, description=null, priority=HIGH, done=true]
records equal by value: true
hash codes equal: true
internalNotes never reaches the response, and the client could not set it even if it tried — CreateTaskRequest simply has no such component.
curl -s -X PATCH localhost:8080/api/tasks/7 -H "Content-Type: application/json" \
-d '{"priority":"HIGH","done":true,"internalNotes":"hacked"}'{"id":7,"title":"Write tests","description":null,"priority":"HIGH","done":true,"projectName":"Website"}
The unknown internalNotes property is ignored by Jackson and has no effect.
Compact constructors for normalisation
Records can validate or normalise in a compact constructor, which runs for every instance — including those Jackson creates:
import java.util.List;
record TagList(List<String> tags) {
TagList {
tags = tags == null ? List.of()
: tags.stream().map(String::strip).map(String::toLowerCase).distinct().sorted().toList();
}
}
class Main {
public static void main(String[] args) {
System.out.println(new TagList(List.of(" Work", "urgent ", "work", "Home")));
System.out.println(new TagList(null));
}
}TagList[tags=[home, urgent, work]]
TagList[tags=[]]
Where should mapping live?
| Option | Pros | Cons |
|---|---|---|
static from(...) / toEntity() on the DTO |
simple, no extra classes | DTO knows the entity |
a TaskMapper @Component |
keeps DTOs pure, easy to test | one more class |
| MapStruct (code generator) | no hand-written boilerplate for big models | build-time tool to learn |
Start with hand-written mapping; it is explicit and the compiler catches mistakes. Reach for MapStruct when you have dozens of similar DTOs.
Tip: Name DTOs after their purpose (
CreateTaskRequest,TaskSummary,TaskDetails) rather than genericTaskDto. Different endpoints often need different shapes, and that is fine.
Test yourself
Which is NOT a good reason to use DTOs instead of returning JPA entities?
- Avoid exposing sensitive fields
- Prevent clients from setting fields they should not
- Make JSON serialisation impossible
- Decouple the API from the database schema
What do Java records generate automatically?
- Setters
- A no-arg constructor
- Accessors, canonical constructor, equals, hashCode and toString
- Database tables
Where can a record normalise its input (e.g. trim strings) for every instance?
- In a compact constructor
- In a setter
- In
toString() - It cannot