假设一个作者写了很多书,而且很多书只有一个作者。
所以这是一个双向的关系。
当您尝试对其进行序列化时,它会变成这样的书籍和作者的无限循环:
{
"id": 1,
"name": "1984",
"author": {
"id": 1,
"name": "George Orwell",
"books": [
{
"id": 1,
"name": "1984",
"author": {
"id": 1,
"name": "George Orwell",
"books": [
{
"id": 1,
"name": "1984",
"author": {
...etc.
这两个注释 (@JsonManagedReference
和@JsonBackReference
) 帮助我们打破这个循环:
@Entity
public class Book {
@ManyToOne
@JoinColumn(name = "author_id")
@JsonManagedReference
private Author author;
}
@Entity
public class Author extends AbstractEntity {
@OneToMany(mappedBy = "author", fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
// @JsonIgnore
@JsonBackReference
private Set<Book> books;
}
但是使用此解决方案,您可以访问具有适当作者的书籍
{
"id": 1,
"name": "1984",
"author": {
"id": 1,
"name": "George Orwell"
}
}
,但您可以访问作者及其书籍:
{
"id": 1,
"name": "George Orwell"
}
有人已经解决了这个问题吗?还是只是从一侧访问完整信息的方式?
谢谢您的帮助
乔斯