【发布时间】:2017-09-14 20:01:48
【问题描述】:
我正在开发一个 EclipseLink 项目,其中一个用户可以像在社交媒体网站上那样“关注”另一个用户。我使用User 实体(引用名为users 的表)进行了此设置,该实体具有“关注者”列表(关注该用户的用户)和另一个“关注者”列表(用户关注的用户)。该关系在名为 followers 的单独表中定义,其中包含关注用户 ID (user_id) 和关注用户 ID (follower_id) 的列。
我的用户模型如下所示:
@Entity
@Table(name = "users")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM USER u")
public class User {
// other attributes
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "follower", joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "follower_id", referencedColumnName = "id"))
private List<User> followers;
@ManyToMany(mappedBy = "followers")
private List<User> following;
// other getters and setters
public List<User> getFollowers() {
return this.followers;
}
public List<User> getFollowing() {
return this.following;
}
}
getFollowers() 方法似乎工作正常,但是当调用 getFollowing() 时,我收到一堆控制台垃圾邮件,最终导致 StackOverflowException:
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion
(StackOverflowError) (through reference chain:
org.eclipse.persistence.indirection.IndirectList[0]-
>org.myproject.model.User["followers"]-
>org.eclipse.persistence.indirection.IndirectList[0]-
>org.myproject.model.User["following"]-
...
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase
.serializeFields(BeanSerializerBase.java:518)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize
(BeanSerializer.java:117)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer
.serializeContents(IndexedListSerializer.java:94)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer
.serializeContents(IndexedListSerializer.java:21)
...
如果我应该提供更多堆栈跟踪,请告诉我。有什么提示吗?
【问题讨论】:
-
@JacksonIgnore for your collection 应该可以解决您的问题
-
确实如此(假设您的意思是
@JsonIgnore)。你是救生员! -
你能反序列化而不丢失信息吗?
-
我不需要通过 JSON 发送有关关注者的信息,因此丢失这些信息对我来说不是问题。
标签: java postgresql jpa eclipselink