1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jeff
  • 3,618
  • 9
  • 48
  • 101

1 Answers1

1

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();
}
Brian Vosburgh
  • 3,146
  • 1
  • 18
  • 18
  • OK, I'm getting org.hibernate.LazyInitializationException: could not initialize proxy - no Session. My query is select p from Project p left join fetch p.projectLead lead_emp_no left join p.projectLead.boss Again, I'm trying to get a list of all projects with columns for lead, leadBosses and leadBossesBoss – jeff Feb 18 '16 at 18:57
  • so I was using (fetch = FetchType.LAZY) on the @OneToOne and if I remove that, then I'm getting the first level or bosses, al beit, I think hibernate is hitting the database more than once (need to investigate that more) now to see if the 2nd level of bosses can be retrieved – jeff Feb 18 '16 at 19:15