JPA双向一对多关系的JSON无限循环问题

5

在这个特定环境下的程序: EJB3.0 + JPA + Jersey Web Service

第一个实体:

@Entity
@Table(name = "student_by_test_yao")

public class StudentTest implements Serializable {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    @ManyToOne
    @JoinColumn(name = "class_id")
    private ClassTest classes;

    public StudentTest() {}
}

第二实体:

@Entity
@Table(name = "class_by_test_yao")
public class ClassTest implements Serializable{
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    @OneToMany(mappedBy = "classes",cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    private List<StudentTest> students;

    public ClassTest() {}
}

当我获取ClassTest的学生名单时,出现异常:
com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError)

如果我将fetch FetchType.LAZY更改为其他值,会出现以下异常:

org.hibernate.LazyInitializationException: 
failed to lazily initialize a collection of role: 
cn.gomro.mid.core.biz.goods.test.ClassTest.students, 
could not initialize proxy - no Session

如何解决我的问题?

这可能会有帮助。避免循环的最佳方法。 - sp518
对于任何遇到此问题的人,最好的解决方案是:https://dev59.com/inA75IYBdhLWcg3wYX9Q#18288939 - Olezt
4个回答

5
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;

这真的有效。我刚刚在双向 @ManyToOne 映射上尝试了一下,它修复了

com.fasterxml.jackson.databind.JsonMappingException: 无限递归(StackOverflowError)


3
尝试在一个字段上添加@JsonIgnore注解,以避免循环。

@JsonIgnore是无用的。仍然在'org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:167)'中发生异常。导致原因是:com.fasterxml.jackson.databind.JsonMappingException: 无限递归(StackOverflowError) - Adam Yao
嗯,奇怪。当我遇到相同的异常时,它帮了我。 - Vyacheslav Tsivina

1

实际上,我需要在ClassTest中获取List,也需要在StudentTest中获取Entity。 - Adam Yao
抱歉,我不确定我理解了您的意思。 您想从ClassTest中获取StudentTest,或者从StudentTest中获取ClassTest吗? - Alexander H
1
使用 @JsonManagedReference 和 @JsonBackReference,您应该能够在反序列化期间重建关系的双向性。当然,在 JSON 表示中,关系的两个方向都不会被序列化,否则您将遇到堆栈溢出问题,因为实体将继续相互引用。 - Alexander H
@AlexanderH 所以我相信 OP 试图做的事情是不可能的,但是如果我只想要 List<?>.length 呢?也许可以在不引起无限递归的情况下从相反的角度看到有多少关系存在。 - medley56
我会在 ClassTest 中定义一个 @JsonProperty,类似这样:@JsonProperty public int classSize() { return classes.getStudents().size(); } - Alexander H

1

代码片段必须帮助您。

@JsonIgnore
@ManyToOne
@JoinColumn(name = "columnName", referencedColumnName = "id")
private Class class;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接