项目是基于JPA的持久性与两个实体(部门和雇员)部门(一对多)和雇员(多对一)每当我通过API发送请求有一个StackOverFlow错误。到目前为止,我追溯的主要原因是堆栈是满的是不确定的递归。有人能解释为什么通常会发生这种情况,它不应该有混淆的双向关系的实体。
package com.springjpacrud01.model;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY)
List<Employee> employees;
public Department() { }
public Department(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "position")
private String position;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
public Employee(Long id, String name, String position) {
this.id = id;
this.name = name;
this.position = position;
}
public Employee() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
在我刚刚删除了部门实体的getter/setter之后,它工作了,但是它不应该像那样工作,我想知道为什么我不能做指向其他实体的关系?我猜它不能形成JSON响应是因为指向其他实体的无限递归。我怎样才能有效地解决这个问题,以便通过部门ID检索员工,谢谢)
1条答案
按热度按时间r3i60tvu1#
如果有人需要它,我已经解决了这个问题,通过了解深层原因,这是@JoinColumn创建和寻址到空的公共列,我手动删除。通过雇员存储库调用雇员的id Hibernate陷入了一个无限循环:先到雇员存储库,然后从雇员存储库到部门存储库,再到部门存储库为了停止这种情况,我通过配置部门
@OneToMany(mappedBy = "department", cascade= CascadeType.ALL, orphanRemoval=true) private Set<Employee> employeeHashSet = new HashSet<>();
And来Map不同的关系