Spring MVC + Hibernate&杰克逊=无法写JSON:无限递归

时间:2014-04-14 22:58:13

标签: java json spring hibernate

我知道这已被问过很多次了,解决方案非常明显,但在我的情况下它并没有真正起作用,我无法弄清楚如何解决它。

问题Could not write JSON: Infinite recursion (StackOverflowError)

设置如下:

员工属于某个部门。 (多对一) 部门有一名员工担任经理。 (OneToOne)

我不想在部门中拥有@OneToMany列表,因此缺少了拥有方。 员工有一个部门对象,但这是它所属的部门,而不是他管理的部门。

Employee.java

@Entity
@Table(name = "ts_employee")
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@emp_id")
public class Employee extends AbstractEntity {

    @ManyToOne
    @JoinColumn(name = "dept_id")
    @JsonManagedReference
    private Department department;

    ... getters and setters
}

Department.java

@Entity
@Table(name = "ts_department")
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@dept_id")
public class Department extends AbstractEntity {

    @OneToOne
    @JoinColumn (name = "manager_id")
    @JsonBackReference
    private Employee manager;

    .. other fields.. getters and setters
}

AbstractEntity.java

@MappedSuperclass
public class AbstractEntity implements Serializable {

    @Id
    @GeneratedValue()
    private Long id;
    ... getters and setters

}

我尝试了两种解决方案:

  1. @JsonBackReference + @JsonManagedReference 我摆脱了StackOverflow,但是Department.manager没有被序列化(@JsonBackReference),并且没有在响应中发送,这很糟糕。

  2. @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,property =“@ emp_id”),它似乎没有做任何事情,而StackOverflow被抛到了我的脸上:(

  3. 如何在不修改模型类的情况下解决这个问题呢?

    非常感谢:)

1 个答案:

答案 0 :(得分:5)

@JsonBackReference不会被序列化。 如果可能,请尝试使用@JsonIdentityInfo而不是@JsonManagedReference@JsonBackReference。关注this link以获取文档。

如果您不需要在此过程中进一步维持关系,也可以尝试使用@JsonIgnore