Neo
Neo

Reputation: 31

Many To Many JPA Annotations more than two tables

Currently I have three tables. User, Role and Institution.

As you know user and roles has many to many relation. (One user can have multiple roles, one role can have multiple users).

Create a many to many annotations as follows.

#In User Table.
@ManyToMany
@JoinTable(name = "USER_ROLES",
        joinColumns = {@JoinColumn(name = "USER_ID")},
        inverseJoinColumns = {@JoinColumn(name = "ROLE_ID")}
)
private Set<Role> roles = new HashSet<Role>();

#In Role Table.
@ManyToMany
@JoinTable(name = "USER_ROLES",
        joinColumns = {@JoinColumn(name = "ROLE__ID")},
        inverseJoinColumns = {@JoinColumn(name = "USER_ID")}
)
private Set<User> users = new HashSet<User>();

But later I have realized that a user can have a role in one institution and a different role in another Institution or the same in different institutions. How can I set that relation?

Upvotes: 1

Views: 445

Answers (1)

JB Nizet
JB Nizet

Reputation: 691785

First of all, your simple many to many mapping is wrong. One side of the bidirectional association must be the inverse side, using the mappedBy attribute. For example:

@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<User>();

Now to answer your question, you just need one more entity. Let's call it Participation. A participation contains a role of a given user in a given institution. So, you have the following locical associations:

  • user - OneToMany - participation
  • participation - ManyToOne - role
  • participation - ManyToOne - institution

Upvotes: 1

Related Questions