gpt4 book ai didi

具有自引用类的Java Hibernate json无限递归

转载 作者:行者123 更新时间:2023-11-30 07:52:46 26 4
gpt4 key购买 nike

类员工:

@Entity
@Table(name = "Employee")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "EmployeeID")
private int EmployeeID;

@Column(name = "ManagerID")
private Integer ManagerID;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="ManagerID", insertable = false, updatable = false)
@JsonBackReference
private Employee manager;

@OneToMany(mappedBy="manager")
@JsonManagedReference
private Set<Employee> employees;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name = "DepartmentID")
private Department department;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name = "SalaryTypeID")
private SalaryType salaryType;

@Column(name = "Name")
private String Name;
//setters and getters here, wont be posting them
}

每当我创建一个员工实例时,我都会收到这个无限的 json 错误:

SEVERE: Servlet.service() for servlet [SpringMVC] in context with path 
[/SpringMVC] threw exception [Handler processing failed; nested exception is
java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError
at java.nio.CharBuffer.<init>(Unknown Source)
at java.nio.HeapCharBuffer.<init>(Unknown Source)
at java.nio.CharBuffer.wrap(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)
at com.google.gson.stream.JsonWriter.string(JsonWriter.java:534)
at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:402)
at com.google.gson.stream.JsonWriter.value(JsonWriter.java:495)

(然后继续)

由于我是自引用经理,是员工类中的一名员工,我该如何解决这个问题?

最佳答案

有很多选项取决于您的要求:

1) @JsonIgnore 可用于避免字段序列化。

@OneToMany(mappedBy="manager")
@JsonIgnore
private Set<Employee> employees;

2) @JsonView 可以将关系的一部分隐藏为内部 View (但如果您使用 Internal 编写 JSON 对象,则会出现 View ):

@OneToMany(mappedBy="manager")
@JsonView(Views.Internal.class)
private Set<Employee> employees;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name = "DepartmentID")
@JsonView(Views.Public.class)
private Department department;

3) Using custom serialiazer您可以自己确定构建 JSON 对象的规则。

4) 在类上使用 @JsonIdentityInfo(以指示该类型的属性应该启用功能)以及在单个属性上(以支持类型本身的情况不能注解;或者使用不同的id生成顺序)。

Example 1 @JsonIdentityInfo

Example 2 @JsonIdentityInfo

关于具有自引用类的Java Hibernate json无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45362300/

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