我有两个表部门和员工。 Department是Employee的父级,两者都由department_id加入。
系
@Entity
public class Department {
@Override
public String toString() {
return "Department [departmentId=" + departmentId + ", departmentName=" + departmentName + "]";
}
@Id
public Integer departmentId;
public String departmentName;
@OneToMany(mappedBy = "department",fetch=FetchType.LAZY)
public Set<Employee> employees;
}
员工
@Entity
public class Employee {
@Override
public String toString() {
return "Employee [employee_id=" + employeeId + ", employee_name=" + employeeName + ", department="
+ department + "]";
}
@Id
public Integer employeeId;
public String employeeName;
@ManyToOne
@JoinColumn(name = "departmentId")
public Department department;
}
当我尝试检索所有部门细节时,它正在创建一个循环依赖项,而jackson正在抛出以下错误。 所以我想知道如何处理这个案例,您需要灵活地从父级访问子详细信息并从子级访问父级详细信息。
2017-08-01 12:03:13.245 WARN 18197 --- [o-auto-1-exec-3]
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message:
org.springframework.http.converter.HttpMessageNotWritableException: Could not
write JSON: Infinite recursion (StackOverflowError); nested exception is
com.fasterxml.jackson.databind.JsonMappingException:
答案 0 :(得分:1)
我能够使用以下方法@JsonIgnoreProperties实现此解决方案。通过这种方式,我能够在员工的部门和部门级别详细信息中获取员工详细信息并避免无限递归
@JsonIgnoreProperties("department")
@OneToMany(mappedBy = "department",fetch=FetchType.EAGER)
public Set<Employee> employees;
@JsonIgnoreProperties("employees")
@ManyToOne
@JoinColumn(name = "departmentId")
public Department department;
答案 1 :(得分:0)
您可以使用@JsonManagedReference
和@JsonBackReference
:
@JsonBackReference
public Department department;
并在部门模型中
@JsonManagedReference
public Set<Employee> employees
它现在应该工作:)
答案 2 :(得分:-1)
是的,这是预期的,杰克逊将迭代你的引用,因为关系是双向的,它将陷入无限的操作。
要解决此问题,您可以使用@JsonIgnore
忽略序列化关系的一侧以打破循环
@Entity
public class Employee {
@Override
public String toString() {
return "Employee [employee_id=" + employeeId + ", employee_name=" + employeeName + ", department="
+ department + "]";
}
@Id
public Integer employeeId;
public String employeeName;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "departmentId")
public Department department;
}