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

Avoiding Endless JSON

When objects point back.

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

An author has books. Each book has an author. That author has books, and so on, forever. If we send entities straight to Jackson, it can get stuck in this loop.

  • Author → books
  • Book → author
  • Forever

An endless loop

This controller returns the Author entity itself. We also keep the session open, during JSON writing, so the lazy books can load. Run it. We print the first three lines of the response. Jackson goes author, books, author, books, again and again. The response is almost fifteen thousand characters long, repeating the same data, until Jackson reaches its nesting limit. For a big author, this could crash the server.

AuthorController.javajava
@RestController
public class AuthorController {

    private final AuthorRepository authors;

    public AuthorController(AuthorRepository authors) { this.authors = authors; }

    @GetMapping("/authors/{id}")
    public Author one(@PathVariable Long id) {
        return authors.findById(id).orElseThrow();
    }
}
Output
$ curl localhost:8080/authors/1 | fold -w 80 | head -3
{"id":1,"name":"Frank Herbert","books":[{"id":1,"title":"Dune","price":9.99,"aut
hor":{"id":1,"name":"Frank Herbert","books":[{"id":1,"title":"Dune","price":9.99
,"author":{"id":1,"name":"Frank Herbert","books":[{"id":1,"title":"Dune","price"
$ curl localhost:8080/authors/1 | wc -c
   14651
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
spring.jpa.open-in-view=true
Also uses _curl.sh
curl localhost:8080/authors/1 | fold -w 80 | head -3
curl localhost:8080/authors/1 | wc -c
Also uses _log
none

Three fixes

There are three common fixes. At Json Ignore on one side, stops Jackson following that field. At Json Managed Reference, and Back Reference, keep one direction only. But the cleanest fix is a DTO, which simply has no loop.

FixHow
@JsonIgnoreskip one side of the loop
@JsonManagedReference / @JsonBackReferenceone direction only
DTO (best)no loop to follow

The DTO fix

Author DTO holds the name, and a list of titles. Plain strings, so there's no loop. At Transactional read only keeps the session open while we build it. Run it. Frank Herbert comes back with two titles, and nothing more.

AuthorController.javajava
@RestController
public class AuthorController {

    record AuthorDto(String name, List<String> titles) {}

    private final AuthorRepository authors;

    public AuthorController(AuthorRepository authors) { this.authors = authors; }

    @GetMapping("/authors/{id}")
    @Transactional(readOnly = true)
    public AuthorDto one(@PathVariable Long id) {
        Author a = authors.findById(id).orElseThrow();
        var titles = a.getBooks().stream().map(Book::getTitle).toList();
        return new AuthorDto(a.getName(), titles);
    }
}
Output
{"name":"Frank Herbert","titles":["Dune","Children of Dune"]}
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 _curl.sh
curl localhost:8080/authors/1

Summary

Entities that point at each other can loop forever, in JSON. At Json Ignore can break the loop, but DTOs avoid it completely. Next, some practice.

Key takeaways
  • Loops in JSON
  • @JsonIgnore
  • DTOs: no loops
Next up: Practice: Authors and Books — your turn