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

    DTO Design

    DTOs (Data Transfer Objects) are the shapes you expose at API boundaries.

    Course progress0%
    Focus
    4 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    DTOs (Data Transfer Objects) are the shapes you expose at API boundaries. Never leak JPA entities — they couple your DB schema to your public API and break the moment you refactor.

    Understanding the topic

    Three flavours of DTO:

    • Request DTOs — the shape you accept (NewOrder, UpdateProfile).
    • Response DTOs — the shape you return (OrderDto, UserSummary).
    • Internal DTOs — between services or aggregates, not over HTTP.

    Informative example

    ts
    // Records make perfect immutable DTOs
    public record NewOrder(
    @NotNull Long userId,
    @NotEmpty List<@Valid LineItem> items,
    @Pattern(regexp = "[A-Z]{3}") String currency
    ) {
    public record LineItem(@NotNull Long productId, @Positive int qty) {}
    }
    public record OrderDto(Long id, String status, int totalCents, Instant createdAt) {}

    Best practices

    • Use Java records for DTOs — immutable, concise, free equals/hashCode.
    • Validate at the DTO level with Bean Validation annotations.
    • Map entity↔DTO with MapStruct or hand-written mappers — never expose entities.
    Ready to mark this lesson complete?Track your journey across the entire course.