Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - multiple many-to-many associations between two classes

Tags:

java

hibernate

I have two entities, call them A and B. Those entities may be in one of three different many-to-many relationships with one another.

How would I model that in Hibernate? The idea is that class A would have fields:

Set<B> relationX;
Set<B> relationY;
Set<B> relationZ;

And similarly class B would have fields:

Set<A> relationX;
Set<A> relationY;
Set<A> relationZ;

The two classes both have all three fields, because I want the association to be bidirectional.

Having the "standard" Hibernate many-to-many annotation like this one...

@JoinTable(name = "A_relX_B",
        joinColumns = {@JoinColumn(name = "A_ID")},
        inverseJoinColumns = {@JoinColumn(name = "B_ID")}
)

... would not work, as there is no way to differentiate between the three separate relations. How would I achieve that? Or do I need to manually decompose the m-to-n relationship?

like image 977
Martin Melka Avatar asked Nov 25 '25 04:11

Martin Melka


1 Answers

You are already on the right way:

public class A {
  @ManyToMany
  @JoinTable(name = "A_relX_B",
    joinColumns = {@JoinColumn(name = "A_ID")},
    inverseJoinColumns = {@JoinColumn(name = "B_ID")}
  )
  Set<B> relationX;

  @ManyToMany
  @JoinTable(name = "A_relY_B",
    joinColumns = {@JoinColumn(name = "A_ID")},
    inverseJoinColumns = {@JoinColumn(name = "B_ID")}
  )
  Set<B> relationY;

  @ManyToMany
  @JoinTable(name = "A_relZ_B",
    joinColumns = {@JoinColumn(name = "A_ID")},
    inverseJoinColumns = {@JoinColumn(name = "B_ID")}
  )
  Set<B> relationZ;
}

Basically, these are independent associations, you can have one (most common case) or a hundred of them as long as each is mapped to a separate relationship table.

The same is on the B side (don't forget mappedBy to pick the inverse side on each association).

like image 149
Dragan Bozanovic Avatar answered Nov 27 '25 17:11

Dragan Bozanovic