具有层次关系的JPA实体

时间:2016-02-17 19:40:34

标签: sql jpa entity connect-by

我有以下实体

@Entity 
public class Project implements Serializable { 
    @Id
    private Integer project_id;
    private String project_name;
    other attributes

    @OneToOne
    @JoinColumn(name = "lead_emp_no", referencedColumnName = "emp_no")
    private Employee projectLead;

    //  but the following two relationships need to be a connect by:
    @OneToOne
    @JoinColumn(name = "lead_boss_emp_no", referencedColumnName = "emp_no")
    private Employee projectLeadBoss;

    @OneToOne
    @JoinColumn(name = "lead_bosses_boss_emp_no", referencedColumnName = "emp_no")
    private Employee projectLeadBossesBoss;

通过此设置,我们必须手动维护Lead的老板和Lead的Boss老板的员工编号。知道projectLead员工后,[某种程度上]已经可以获得这种关系:

员工实体如下:

  @Entity
  public class Employee implements Serializable {
  @Id
  private Integer emp_no;
  private Integer bosses_emp_no;

是否可以让我的Project实体连接到老板并根据projectLead老板员工?在单个查询中,我想获得所有项目及其主要层次结构的表格。我对实体重新设计持开放态度。

1 个答案:

答案 0 :(得分:1)

您可以使用更有帮助的bosses_emp_no替换Employee中的boss

@Entity
public class Employee implements Serializable {

    @Id
    private Integer emp_no;

    @OneToOne
    @JoinColumn(name = "boss_emp_no", referencedColumnName = "emp_no")
    private Employee boss;

然后,您只需向Project

添加几个委派方法
public Employee getProjectLeadBoss() {
    return this.projectLead.getBoss();
}

public Employee getProjectLeadBossesBoss() {
    return this.getProjectLeadBoss().getBoss();
}