【问题标题】:Is it okay to have more than one foreign key from one table to the same table?从一张表到同一张表可以有多个外键吗?
【发布时间】:2020-10-02 05:20:59
【问题描述】:

假设我有一个如下所示的表格:-

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;

}
}

当我编译和运行时,上面没有给我任何问题。

所以我的问题基本上是可以让一个表与其自身或另一个表具有多个外键关系,或者如果我遵循这个模式,我以后会遇到一些麻烦。

谢谢,

【问题讨论】:

  • 我无法回答问题的弹簧启动方面,但从数据库的角度来看,您不能添加指向多行的外键。此外,这会引入不必要的冗余,因为管理器的外键已经包含完整的信息。下属列表不应在数据库中建模。

标签: mysql spring postgresql spring-boot


【解决方案1】:

在大多数情况下,您不想要一对一的关系。您将 2 个具有 1 对 1 关系的表合并为一张表。

在您的示例中,managerId 和员工关系是 1 比 1。 合并它们:将表重命名为员工/经理,并将 managerId 列替换为布尔列“isManager”,如果该员工是经理则取值为 1,否则为 0。

其他下属栏没问题。 您可以在表格本身内进行 1 到多个 relashionship。

但是您应该考虑实现以及将外键放置在一对多关系中的位置。 例如:一个部门可以有多个员工,但一个员工只能在一个部门。这是一对多的关系。但是在实现的时候,外键应该在employees表中引用department表。

也是对您问题的一般回答:

是的。如果不可避免,您可以对同一个表有多个外键。 还要避免 2 个表之间存在 1 对 1 的关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    相关资源
    最近更新 更多