Reputation: 7789
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?
Upvotes: 3
Views: 786
Reputation: 23552
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).
Upvotes: 4
Reputation: 991
I don't know if there's an easy way to accomplish this without normalizing the many-to-many relationships out of your tables. Having many-to-many relations in a relational database is typically considered to be a no-no, and would require cross-referencing tables to manage them.
Upvotes: 0