如何在Hibernate / JPA中避免双向关系上的StackOverflow?

时间:2018-10-22 17:40:23

标签: java json spring hibernate spring-data-jpa

我正在考虑如何避免查询中出现StackOverflow。我需要双向关系,因为一旦我要求Happening来获得其中的Place,而另一种方式我就会要求Place来达到Happenings。 但是现在,当我请求Happening时,由于Place包含Set中的Happenings而使我感到堆栈溢出。我在做什么错了?

public class Happening {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToOne
    private Place place;
}
public class Place {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "place")
    private Set<Happening> happenings;
}

使用我要求的JPA存储库

public Happening getHappening(Long id) {
    return happeningRepository.findById(id).get();
}

错误

Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.proj.happening.Models.Happening[&quot;place&quot;]-&gt;com.proj.happening.Models.Place

编辑

我尝试从此处使用解决方案:[https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion][1] 但是好吧,当我因发生Set<Happening> happenings;数据丢失而要求进行“发生”时,我没有递归,但是当我想从另一端调用并获得“位置”时,我也就失去了Set<Happening> happenings;。那不是我要找的解决方案。

0 个答案:

没有答案