班级员工:

@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可以将关系的一部分隐藏为内部视图(但是如果使用Internal视图编写JSON对象,则会显示该关系):

@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

10-06 16:11