Search code examples
sqljpaentityconnect-by

JPA Entity with hierachy relationship


I have the following Entity

@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;

With this setup, we have to manually maintain the employee numbers for the Lead's boss and the Lead's Boss's boss. This relationship is [somewhat] already available knowing the projectLead employee:

The Employee Entity is as follows:

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

Is it possible to get my Project entity to connect to the boss and bosses Employee based on projectLead? In single query I'd like to get a table of all projects and their lead's hierarchy. I'm open to entity redesign.


Solution

  • You can replace the bosses_emp_no in Employee should with a more helpful boss:

    @Entity
    public class Employee implements Serializable {
    
        @Id
        private Integer emp_no;
    
        @OneToOne
        @JoinColumn(name = "boss_emp_no", referencedColumnName = "emp_no")
        private Employee boss;
    

    Then you simply add a couple of delegating methods to Project

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