假设我有一张如下所示的桌子:-
Employee
employee Id -- Primary Key
manager Id -- Foreign Key Relationship with employee id as manager is also an employee
subordinates -- List<Employee Ids> another foreign key relationship to the same table.
我用的是spring,所以一个极简课程应该是如下所示的:-
@Data
@Entity(name = "employee")
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
@Column(name = "employee_id", columnDefinition = "VARCHAR(255)", unique = true, nullable = false)
private String employeeId;
@OneToMany(mappedBy = "employee", fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
@JsonManagedReference
private Set<Employee> subordinates;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "employee_id", nullable = false)
@JsonBackReference
private Employee manager;
}
}
当我编译和运行时,上面没有给我任何问题。
所以我的问题基本上是,让一个表与自身或另一个表具有多个外键关系是否可以,或者如果我遵循这个模式,我以后会陷入一些麻烦。
谢谢,
在大多数情况下,你不想要1对1的关系。 合并具有1对1关系的2个表,使它们成为一个表。
在您的示例中,managerId和employee的关系是1比1。 合并它们:将表重命名为employee/manager,并将managerId列替换为布尔列“ismanager”,如果该员工是经理,则取值1,否则取值0。
其他部属纵队没问题。 您可以在表本身内有一个1到多个关系。
但是在中,您应该考虑实现以及在1对多的关系中将外键放在哪里。 例:一个部门可以有多个员工,但一个员工只能在一个部门。 这是一对多的关系。 但是在实现时,外键应该在引用department表的employees表中。
也是对你的问题的一般性回答:
是的。 如果无法避免,可以对同一个表有多个外键。 还要避免两个表之间存在1对1的关系。