DTOs for Relationships
Shape the JSON.
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.
| key | value |
|---|---|
| Choose fields | send only what's needed |
| Flatten | author: "Frank Herbert" |
| Hide | internal fields |
| Freedom | change 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.
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.
@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();
}
}[
{"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=trueAlso 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/booksSummary
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