Skip to main content
PreparationZone Logo
PrepZone

DTOs, Records, and Entity Mapping

Why you never expose entities on REST APIs and how records make DTOs effortless.

Pass checkpoint below

Why this matters

  • Exposing @Entity objects 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 id or createdAt).

Why DTOs

L1 · Fresher

Never 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 · Intermediate

Immutable records with Jackson work well for request/response payloads on Java 21 — less boilerplate than Lombok for simple shapes.

Mapping strategies

L3 · Advanced

Manual mapping, MapStruct, or small mapper beans — pick one per module and stay consistent in BookStore.

API versioning vs DTO evolution

L4 · Expert

Additive JSON fields are safer than changing entity schemas. Version DTOs when breaking clients cannot be updated in lockstep.

SingletonOne instance per container
PrototypeNew instance every injection
RequestOne per HTTP request
SessionOne per HTTP session
Singleton is the default. Choose other scopes when lifecycle must match HTTP session or request.

Why not return entities?

Java
// 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 @ManyToOne relations trigger LazyInitializationException during JSON serialisation.

Response DTO as a record

Java
// 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.