简体   繁体   中英

Can an entity have more than one many-to-many relations?

I have a table that has two different many-to-many relations to two different tables. Let's say I have User <---> UserRole <--> Role and User <--> UserGroups <--> Groups . Since I am new to hibernate and database mapping I was wondering if having my User entity have attributes roles and groups in it, both with @ManytoMany annotations is good practice and acceptable?

ie:

 @Entity(name = "User")
 @Table(name = "USER")
 public class User {

 .... /* Obviously Id would go here and all other attributes */

 @ManyToMany(cascade = CascadeType.ALL)
 @JoinTable(name = "UserRole", joinColumns = { @JoinColumn(name="USER_ID") },
            inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") } )
 private Set<Role> roles = new HashSet<Role>();

 @ManyToMany(cascade = CascadeType.ALL)
 @JoinTable(name = "UserGroup", joinColumns = { @JoinColumn(name="USER_ID") },
            inverseJoinColumns = { @JoinColumn(name = "GROUP_ID") } )
 private Set<Group> groups = new HashSet<Group>();

Sure; lots of types have multiple many-to-many.

I think minimizing many-to-many relationships is a good idea, but it's a natural structure, and is found all over the place.

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