torshid
torshid

Reputation: 167

Relationship entity used to create a hierarchy between objects of a single entity

I have an Organization entity which can have a single parent and/or children. The hierarchy between organizations need to have extra columns (such as relationship type), so I created an entity OrganizationRelationship which is used for parents and also for children. I was able to get the children working with a OneToMany association but couldn't get the parent to work (which should use ManyToOne I guess).

I have an embeddable primary key as follows:

@Embeddable
public class OrganizationParentChildPk implements Serializable {

  @ManyToOne(cascade = CascadeType.ALL)
  public Organization parentOrganization;

  @ManyToOne(cascade = CascadeType.ALL)
  public Organization childOrganization;

}

And then the relationship entity:

@Entity
@Table(name = "ORGANIZATION_LK")
@AssociationOverrides({
    @AssociationOverride(name = "pk.parentOrganization", joinColumns = @JoinColumn(name = "PARENT_ID")),
    @AssociationOverride(name = "pk.childOrganization", joinColumns = @JoinColumn(name = "CHILD_ID"))})
public class OrganizationRelationship implements Serializable {

  @EmbeddedId
  private OrganizationParentChildPk pk = null;

  @Column
  private String relationshipType = null;

}

Finally, this is my organization entity:

@Entity
@Table(name = "ORGANIZATION")
public class Organization extends Party {

  @Column(name = "NAME")
  private String name = null;

  // ???
  private OrganizationRelationship organizationParentRelationship = null;


  @OneToMany(mappedBy = "pk.parentOrganization", cascade = CascadeType.ALL,
      targetEntity = OrganizationRelationship.class)
  private Set<OrganizationRelationship> organizationChildRelationship = null;

}

What I would like is to make the parent relationship field also use the same ORGANIZATION_LK table if that is possible?

I thank you in advance for your help.

Upvotes: 1

Views: 73

Answers (1)

torshid
torshid

Reputation: 167

I managed to get it working using the following annotation:

  @OneToOne(mappedBy = "pk.childOrganization", cascade = CascadeType.ALL,
      targetEntity = OrganizationRelationship.class)
  private OrganizationRelationship organizationParentRelationship = null;

Upvotes: 1

Related Questions