AI Hints
Home›Spring Boot Tutorial›Controller, Service, Repository, Mapping Entities to DTOs and Update Requests
Spring Boot · Lesson 83 of 120

Mapping Entities to DTOs

Request and response shapes.

⏱ 2 min read▶ Video at 1:51:25🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Our app uses two kinds of DTO. One for what comes in, and one for what goes out. Neither of them is the entity.

  • DTO in
  • DTO out
  • Never the entity

Request and response DTOs

The request DTO holds only what the client may send. So no id, because the database picks it. It also carries the validation rules. The response DTO holds what the client may see, including the id.

CreateBook (in)

  • title, author, priceNo idValidation rules

BookResponse (out)

  • id, title, author, priceWhat the client seesNo rules needed

The two records

Create book has three fields, each with a rule. Book response has four fields. Its static from method maps an entity, to a response.

CreateBook.java · BookResponse.javajava
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}

public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}

Why not use the entity?

If clients could send the entity, they could set fields they shouldn't, like the id. Entity changes would break the API. And lazy relationships could explode the JSON. DTOs keep the API stable, and safe.

keyvalue
Safetyclients can't set the id
Stabilityentity changes stay hidden
JSONno lazy surprises
Mappinga static from() method

Summary

Use a request DTO for input, and a response DTO for output. Map them in the service. Next, update requests.

Key takeaways
  • CreateBook in
  • BookResponse out
  • from(entity)
Next up: Update Requests — PUT through the layers