Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 20

    DTO Design

    A DTO (data transfer object) is the JSON shape Orders exposes or accepts.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A DTO (data transfer object) is the JSON shape Orders exposes or accepts. In Java 21, records are the default: CreateOrderRequest in, OrderView out.

    Do not reuse persistence entities as DTOs. Entities change with indexes and relations; APIs change with clients. Mapping in the service (or a dedicated mapper) keeps both free to evolve.

    Request DTOs include only client-writable fields. Response DTOs include only what clients may see. Internal flags, cost fields, and audit columns stay off the wire.

    Validation annotations live on request DTOs; they are not a substitute for domain checks in the service.

    Purpose of this lesson

    Design Orders request/response records that prevent over-posting and hide persistence details.

    Understanding the topic

    Separate models at the boundary.

    • Request records: sku, qty — not id, not status.
    • Response records: id, status, amountCents, timestamps you intend to publish.
    • Mapping: service methods accept/return DTOs or map at the controller edge consistently.
    • Versioning: additive fields are safer than renames.
    • Nulls: prefer explicit optional fields over ambiguous nulls in JSON.

    Step-by-step explanation

    1. Define CreateOrderRequest and OrderView.
    2. Stop returning maps or entities from controllers.
    3. Map in OrderService.place from request → domain → view.
    4. Add a field to the entity later without changing the response record until you mean to.

    Informative example

    Split request and response.

    java
    public record CreateOrderRequest(
    @NotBlank String sku,
    @Min(1) int qty
    ) {}
    public record OrderView(
    long id,
    String sku,
    String status,
    int amountCents,
    Instant createdAt
    ) {}

    Real-world use

    When finance adds internal margin columns to the order table, mobile must not suddenly receive them. DTOs are the firewall between TechLearningPRO's schema and the public app.

    Security implications

    DTO mistakes are authorization and privacy bugs.

    • Never accept status=SHIPPED from the client on create.
    • Strip PII from responses that support tools should not show to learners.
    • Avoid binding nested objects you do not fully validate.

    Best practices

    • Name DTOs by use case (CreateOrderRequest), not OrderDTO for everything.
    • Keep records immutable.
    • Contract-test JSON for critical DTOs.

    Common mistakes

    • One mega DTO shared by create, update, and admin screens.
    • Exposing entity getters annotated with JSON as a shortcut.
    • Putting service logic inside DTO constructors.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy not return JPA entities from REST controllers?+

    Answer

    It couples API clients to the schema, risks lazy-loading failures, and makes over-exposure likely.
    2IntermediateQuestionRequest DTO vs response DTO?+

    Answer

    Requests model what clients may send; responses model what they may see. Fields rarely match 1:1.
    3IntermediateQuestionWhere should mapping live?+

    Answer

    Usually in the application service (or an explicit mapper). Controllers should stay free of field-by-field noise when possible.

    Hands-on exercise

    Lab. Introduce CreateOrderRequest and OrderView. Attempt to post a status field and ensure it cannot change server state.

    Summary

    Orders DTOs protect clients and the database from each other. Next you translate failures into stable HTTP errors.

    Ready to mark this lesson complete?Track your journey across the entire course.