Mats
Mats

Reputation: 165

JPA: How do I set up an entity with several children and several parents of same entity type?

I'm trying to model a business entity, where said business can have several parent businesses and several child businesses. I'm not sure which relationships are suited, or even what mapping is appropriate. I'm familiar with SQL but new to ORM in Java.

My thinking is that a business can have many or none children, and a business can have many or none parents. Therefore I've tried setting both as OneToMany but also as OneToMany, both resulting in this error: Illegal use of mappedBy on both sides of the relationship.

The implementation:

@Entity
public class Business{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "parentOrgs")
    private Collection<Business> chlidOrgs;

    @OneToMany(mappedBy = "chlidOrgs")
    private Collection<Business> parentOrgs;

    // --- Getters and setters below ---

What am I not understanding here? Any and all help much appreciated.

Upvotes: 0

Views: 391

Answers (1)

Mikko Maunu
Mikko Maunu

Reputation: 42084

Your current mapping is syntactically incorrect, because only one side of the relationship can be owning side. Owning side is the field defined by value of mappedBy attribute. More detailed explanation can be found from here.

Also removing mappedBy from the one side does not solve the problem, because counterpart of OneToMany must be ManyToOne. Removing it from the both sides leaves us with two unirectional associations, which is also not what is needed.

Because each Business can have multiple parents and it seems to be preferred to be able to navigate directly to the childrens as well, solution is to use bidirectional ManyToMany:

@Entity
public class Business {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToMany(mappedBy = "parents")
  private Collection<Business> childrens;

  @ManyToMany
  private Collection<Business> parents;
}

From database point of view this means following tables:

Business(id)
Business_Business(childrens_id, parents_id)

When necessary, name of the join table and columns can be controlled via JoinTable.

Upvotes: 1

Related Questions