【问题标题】:JPA Bidirectional Onetomany json endless loopJPA双向Onetomany json无限循环
【发布时间】:2017-01-09 00:00:29
【问题描述】:

这个特定环境下的程序: EJB3.0 + JPA + jersey Web 服务

第一个实体:

@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

如何解决我的问题?

【问题讨论】:

标签: java json hibernate jackson


【解决方案1】:
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;

确实有效。我刚刚在双向@ManyToOne 映射上进行了尝试。它修复了

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

【讨论】:

    【解决方案2】:

    尝试在其中一个字段中添加@JsonIgnore注解以避免循环

    【讨论】:

    • @JsonIgnore 没用。仍然在 'org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:167) 的例外情况下:com.fasterxml.jackson.databind.JsonMappingException: 无限递归 (StackOverflowError)'
    • 嗯,奇怪。当我遇到相同的异常时,它对我有帮助
    【解决方案3】:

    对于双向关系,您可以使用这些注释:

    @JsonManagedReference 用于父级,@JsonBackReference 用于子级。

    此外,此链接可能会有所帮助: Jackson – Bidirectional Relationships

    【讨论】:

    • 其实我需要在ClassTest中获取List也需要在StudentTest中获取Entity。
    • 抱歉,我不确定我是否明白了。您希望能够从 ClassTest 中获取 StudentTest 并从 StudentTest 中获取 ClassTest 吗?
    • 使用 \@JsonManagedReference 和 \@JsonBackReference 您应该能够在反序列化期间重建关系的两个方向。当然,在 JSON 表示中,关系的双方都没有序列化,否则你会导致堆栈溢出,因为实体会继续相互引用。
    • @AlexanderH 所以我很确定 OP 试图做的事情是不可能的但是如果我只想要 List&lt;?&gt;.length 怎么办?或许可以从对面查看存在多少关系而不会导致无限递归?
    • 我会在ClassTest 一侧定义一个@JsonProperty。比如:@JsonProperty public int classSize() { return classes.getStudents().size(); }
    【解决方案4】:

    片段必须帮助你。

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

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2013-01-05
      • 2014-07-29
      • 1970-01-01
      相关资源
      最近更新 更多