当我尝试调用 REST 端点时,我的 Postman 有一些奇怪的行为。有一个永无止境的循环。我在 stackoverflow 上找到了一个解决方案,@JsonIgnore 注释将删除这个奇怪的循环(我在下面的 Book 实体中有它)但是当我尝试在 Postman 中列出所有书籍时,我看不到这些书籍的作者。是否有更好的解决方案来显示作者的书籍(删除 @JsonIgnore 注释)但也删除那个奇怪的循环?Book.java@Entitypublic 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@Entitypublic 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@RestControllerpublic 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 与 BookController 相同。这是 Book JSON 在 Postman 中的样子(这些书没有作者):Postman 中的 Authors 没问题:这是我从 Book 实体中删除 @JsonIgnore 时的循环:
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
使用@JsonIgnoreProperties注解为了忽略一个字段上的子字段,那么这个注解会忽略二级字段。
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<>();
添加回答
举报
0/150
提交
取消