【发布时间】:2021-01-24 10:02:45
【问题描述】:
我正在使用 Spring Boot、Jackson 和 Hibernate 创建 API。 Hibernate 连接到 MySQL 数据库。 我理解好的做法,但我被困在一个特定的点上。 我有一个包含额外字段的 n:m 关系。
例如:作者(id, ...) -> 书面(idAuthor, idBook, date)
我了解如何映射传统的 n:m 关系,但这次我并不适用这种技术。
为此,我在互联网上找到了一个显示解决方案的来源:在我的代码中创建一个中间类,其中包含一个 Author 类型对象和一个 Book 类型对象 + 我的附加字段。
@Entity
@Table(name = "Author")
public class Author implements Serializable {
/...
@Id
@GeneratedValue
private int id;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private Set<Written> written= new HashSet<>();
/...
}
@Entity
@Table(name = "Book")
public class Book implements Serializable{
/...
@Id
@GeneratedValue
private int id;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
private Set<Written> written= new HashSet<>();
/...
}
public class Written implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "idAuthor")
private Author author;
@Id
@ManyToOne
@JoinColumn(name = "idBook")
private Book book;
//Extra fields ....
}
这是一个双向链接。 使用此代码,我得到一个无限递归错误:
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.exampleAPI.api.model.Book["written"])]
我尝试在 Written 类中使用 @JsonIgnore、@JsonManagedReference 和 @JsonBackReference,也尝试使用 transient 关键字,但没有任何效果。
我在互联网上找不到任何可以帮助我的资源,也找不到此特定案例的文档。
有人可以帮我吗?
【问题讨论】:
标签: java spring-boot hibernate jackson