AI Hints
Home›Spring Boot Tutorial›DTOs for Relationships, Avoiding Endless JSON and Practice: Authors and Books
Spring Boot · Lesson 70 of 120

DTOs for Relationships

Shape the JSON.

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

Entities are shaped for the database. But clients want JSON shaped for them. A DTO, a data transfer object, is a small class made just for the response.

  • Entities fit the database
  • Clients want their own shape
  • DTOs

Why DTOs

With a DTO, you choose exactly which fields to send. Related data can be flattened, like the author's name, instead of a whole author object. Internal fields stay hidden. And you can change the entity, without breaking clients.

keyvalue
Choose fieldssend only what's needed
Flattenauthor: "Frank Herbert"
Hideinternal fields
Freedomchange entities safely

BookDto.java

Book DTO is a record, with four fields. The author is just a name. A static from method copies values, from a Book entity.

BookDto.javajava
public record BookDto(Long id, String title, double price, String author) {

    public static BookDto from(Book book) {
        return new BookDto(book.getId(), book.getTitle(), book.getPrice(),
                           book.getAuthor().getName());
    }
}

Returning DTOs

The controller loads every book, maps each one to a DTO, and returns the list. Run it. Each book is flat, and tidy, with the author's name inline.

BookController.javajava
@RestController
public class BookController {

    private final BookRepository books;

    public BookController(BookRepository books) { this.books = books; }

    @GetMapping("/books")
    public List<BookDto> all() {
        return books.findAll().stream().map(BookDto::from).toList();
    }
}
Output
[
  {"id":1,"title":"Dune","price":9.99,"author":"Frank Herbert"},
  {"id":2,"title":"Children of Dune","price":8.49,"author":"Frank Herbert"},
  {"id":3,"title":"The Hobbit","price":8.99,"author":"J.R.R. Tolkien"},
  {"id":4,"title":"Circe","price":10.99,"author":"Madeline Miller"},
  {"id":5,"title":"Song of Achilles","price":9.49,"author":"Madeline Miller"}
]
Also uses Author.java
@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author")
    private List<Book> books = new ArrayList<>();

    protected Author() {}
    public Author(String name) { this.name = name; }

    public Long getId() { return id; }
    public String getName() { return name; }
    public List<Book> getBooks() { return books; }
}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private double price;

    @ManyToOne
    private Author author;

    protected Book() {}
    public Book(String title, double price, Author author) {
        this.title = title; this.price = price; this.author = author;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public double getPrice() { return price; }
    public Author getAuthor() { return author; }
}
Also uses AuthorRepository.java
public interface AuthorRepository extends JpaRepository<Author, Long> {}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {}
Also uses data.sql
INSERT INTO author (name) VALUES ('Frank Herbert'), ('J.R.R. Tolkien'), ('Madeline Miller');
INSERT INTO book (title, price, author_id) VALUES
  ('Dune', 9.99, 1), ('Children of Dune', 8.49, 1),
  ('The Hobbit', 8.99, 2), ('Circe', 10.99, 3), ('Song of Achilles', 9.49, 3);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses BookDto.java
public record BookDto(Long id, String title, double price, String author) {

    public static BookDto from(Book book) {
        return new BookDto(book.getId(), book.getTitle(), book.getPrice(),
                           book.getAuthor().getName());
    }
}
Also uses _curl.sh
curl localhost:8080/books

Summary

DTOs are records shaped for the client. Map entities to DTOs in the controller, or the service. Next, avoiding endless JSON.

Key takeaways
  • record BookDto
  • BookDto.from(book)
  • Flat JSON
Next up: Avoiding Endless JSON — when objects point back