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

Practice: Authors and Books

Your turn.

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

Let's practise relationships, and DTOs. We'll list one author's books, as tidy JSON.

  • Relationships
  • DTOs
  • One author's books

A query through the relationship

Find by author id, follows the author field, to its id. Order by price sorts them, cheapest first.

BookRepository.javajava
public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthorIdOrderByPrice(Long authorId);
}

An author's books

Your turn. Pause the video, and try this. Add GET slash authors slash id slash books. If the author doesn't exist, return four oh four. Otherwise, return their books as Book DTOs. Here is one solution. Exists by id checks the author first. Then we query the books, and map them to DTOs. Madeline Miller has two books. And author nine doesn't exist.

✍️ Exercise: An author's books

GET /authors/{id}/books → 404 if no such author, else 200 with List<BookDto> (use findByAuthorIdOrderByPrice).

Show hint

authors.existsById(id), then books.findByAuthorIdOrderByPrice(id) mapped with BookDto::from

Show solution
AuthorController.javajava
@RestController
public class AuthorController {
    private final AuthorRepository authors;
    private final BookRepository books;
    public AuthorController(AuthorRepository a, BookRepository b) {
        authors = a; books = b;
    }

    @GetMapping("/authors/{id}/books")
    public ResponseEntity<List<BookDto>> books(@PathVariable Long id) {
        if (!authors.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        var list = books.findByAuthorIdOrderByPrice(id);
        return ResponseEntity.ok(list.stream().map(BookDto::from).toList());
    }
}
Output
$ curl localhost:8080/authors/3/books
[
  {"id":5,"title":"Song of Achilles","price":9.49,"author":"Madeline Miller"},
  {"id":4,"title":"Circe","price":10.99,"author":"Madeline Miller"}
]
$ curl -i localhost:8080/authors/9/books | head -1
HTTP/1.1 404

What module eight taught

Relationships connect entities, through foreign keys. At Many To One, and at One To Many, link books and authors. Lazy loading needs an open session. Cascade saves children with their parent. And DTOs give clean JSON, without loops.

keyvalue
Links@ManyToOne, @OneToMany, @ManyToMany
Loadinglazy needs a transaction
Cascadesave children too
JSONDTOs, no loops

Summary

Your data model now has real relationships. That's the end of module eight. Next module, validation, and error handling.

Key takeaways
  • Relationships
  • Lazy loading
  • DTOs
Next up: Why Validate — never trust input