Reputation: 81
I have some wierd behavior in my Postman when I try to invoke REST endpoints. There is a never-ending loop. I have found a solution on stackoverflow that @JsonIgnore annotation will remove this wierd loop (I have it in my Book entity below) but then when I try to list all books in Postman I do not see authors for those books. Is there a better solution to show books with authors (remove that @JsonIgnore annotation) but also remove that wierd loop?
Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String isbn;
@ManyToMany
@JsonIgnore // removed wierd loop with data
@JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set<Author> authors = new HashSet<>();
public Book() {
}
Author.java
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String forename;
private String surname;
@ManyToMany(mappedBy = "authors")
private Set<Book> books = new HashSet<>();
public Author() {
}
BookController.java
@RestController
public class BookController {
private BookService bookService;
@Autowired
public BookController(BookService bookService) {
this.bookService = bookService;
}
// expose /books and get list of all books - GET
@GetMapping("/api/books")
public List<Book> getAllBooks() {
return bookService.getAllBooks();
}
AuthorController is the same as BookController.
This is how Book JSON looks in Postman (there are no authors for the books):
It's all ok with Authors in Postman:
And this is the loop when I remove @JsonIgnore from Book entity:
Upvotes: 1
Views: 462
Reputation: 5968
Use @JsonIgnoreProperties
annotation in order to ignore the sub fields on a field, then this annotation will ignore the second level fields.
Book
- > authors
-> books // this field is ignored
Author
- > books
-> authors // this field is ignored
@ManyToMany
@JsonIgnoreProperties("books")
@JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set<Author> authors = new HashSet<>();
@ManyToMany(mappedBy = "authors")
@JsonIgnoreProperties("authors")
private Set<Book> books = new HashSet<>();
Upvotes: 1