gpt4 book ai didi

java - Hibernate 具有相同类的多对多,无法编写 JSON : Infinite recursion

转载 作者:行者123 更新时间:2023-11-30 02:24:26 25 4
gpt4 key购买 nike

我在使用 hibernate 和 JSON 时遇到问题,当我对同一个类使用多对多时,我得到了递归

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.util.Set;
import java.util.UUID;

@Entity
public class AssistantGraphVertex {

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private UUID uuid;

@ManyToOne
private AssistantGraphs assistantGraphs;

private String name;
private String description;

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "assistant_graph_edge",
joinColumns = { @JoinColumn(name = "parent_uuid") },
inverseJoinColumns = { @JoinColumn(name = "child_uuid") }
)
private Set<AssistantGraphVertex> parents;

@ManyToMany(mappedBy = "parents")
private Set<AssistantGraphVertex> children;

public UUID getUuid() {
return uuid;
}

public void setUuid(UUID uuid) {
this.uuid = uuid;
}

public AssistantGraphs getAssistantGraphs() {
return assistantGraphs;
}

public void setAssistantGraphs(AssistantGraphs assistantGraphs) {
this.assistantGraphs = assistantGraphs;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Set<AssistantGraphVertex> getChildren() {
return children;
}

public void setChildren(Set<AssistantGraphVertex> children) {
this.children = children;
}

public Set<AssistantGraphVertex> getParents() {
return parents;
}

public void setParents(Set<AssistantGraphVertex> parents) {
this.parents = parents;
}
}

问题如下:

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError);

我只想接收一个类的父类和子类的信息,但对于下一个嵌套类,我不需要这些信息,如何更好地实现这一点?

最佳答案

你可以简单地忽略序列化一侧起诉@JsonIgnore

@JsonIgnore
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "assistant_graph_edge",
joinColumns = { @JoinColumn(name = "parent_uuid") },
inverseJoinColumns = { @JoinColumn(name = "child_uuid") }
)
private Set<AssistantGraphVertex> parents;

@JsonIgnore
@ManyToMany(mappedBy = "parents")
private Set<AssistantGraphVertex> children;

或者您可以使用@JsonIdentityInfo,它将在第二级序列化中为 hibernate 创建引用,这将打破循环

@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class AssistantGraphVertex {

有关更多详细信息,请查看此 link

关于java - Hibernate 具有相同类的多对多,无法编写 JSON : Infinite recursion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com