我有一个表,该表具有一个自引用联接表。
@Entity
public class Employee {
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<EmployeeDependency> employeeDependencies;
}
@Entity
public class EmployeeDependency {
@ManyToOne
@JoinColumn
private Employee employee;
@ManyToOne
@JoinColumn
private Employee employeeDependency;
}
如我们所见,该关系由mappedBy = "employee"
管理。
DB依赖表看起来像这样
EmployeeDependency
----------------------------------------
id employee_id employee_dependency_id
----------------------------------------
1 2 3
2 2 4
3 3 10
现在,当我尝试删除employee= 2
时,它将删除EmployeeDependency
表中的引用,并且还将删除Employee
表中的记录,因为依赖项是由employee
管理的。映射mappedBy = "employee"
。这是预料之中的,并且按其编写的方式工作。
但是现在当我尝试删除关系的另一端的employee = 10
时,我遇到了foreign key
引用错误。
如果我在Employee
实体中放置一个虚拟引用,就可以删除它
@Entity
public class Employee {
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<EmployeeDependency> employeeDependencies;
@OneToMany(mappedBy = "employeeDependency", cascade = CascadeType.ALL, orphanRemoval = true)
private List<EmployeeDependency> dummyEmployeeDependencies;
}
但这似乎不对!如何放置双向级联,以便可以从关系的任一侧删除ID