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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With