【发布时间】: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