简体   繁体   中英

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM