Why this matters
- Exposing
@Entityobjects on REST APIs leaks internal fields, creates tight coupling, and enables lazy-loading exceptions mid-serialisation. - Records (Java 16+) eliminate boilerplate for request and response types.
- Separate read and write DTOs prevent clients from overwriting fields they should not touch (like
idorcreatedAt).
Why DTOs
L1 · FresherNever expose JPA entities on REST APIs — lazy loading and internal fields leak over the wire. Use records or DTO classes for stable JSON contracts.
Java records as DTOs
L2 · IntermediateImmutable records with Jackson work well for request/response payloads on Java 21 — less boilerplate than Lombok for simple shapes.
Mapping strategies
L3 · AdvancedManual mapping, MapStruct, or small mapper beans — pick one per module and stay consistent in BookStore.
API versioning vs DTO evolution
L4 · ExpertAdditive JSON fields are safer than changing entity schemas. Version DTOs when breaking clients cannot be updated in lockstep.
Why not return entities?
// BAD: entity on the wire
@GetMapping("/{id}")
public Book get(@PathVariable Long id) {
return bookService.findById(id); // exposes all fields, lazy relations
}
Problems:
Why entities must not leak to HTTP
- Internal fields (
version, audit columns) become visible. - Changing the database schema breaks API clients.
- Lazy-loaded
@ManyToOnerelations triggerLazyInitializationExceptionduring JSON serialisation.
Response DTO as a record
// learn:fragment
public record BookResponse(
Long id,
String title,
String isbn,
BigDecimal price
) {
public static BookResponse from(Book book) {
return new BookResponse(
book.getId(), book.getTitle(), book.getIsbn(), book.getPrice());
}
}
Immutable, concise, and serialisable by Jackson without configuration.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- Request DTOs: separate create and update
- Mapping in the controller
- Mapping in the service
- List endpoints with summary DTOs
- Nested DTOs
Test yourself
Answer these before moving on — recall is what makes it stick.