hibernate: ternary association mapping

2019-02-20 02:05发布

问题:

Technology Description: Hibernate annotation- 3.4.0.GA java 1.5

table : users_roles_branches columns : user_id, role_id, branch_id

A user is assigned different roles for different branches of a company.

Now i have one java pojo class

     public class branch
     {
                @ManyToMany
             @JoinTable(name = "users_roles_branches", joinColumns = {   @JoinColumn(name="branch_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
             @MapKeyManyToMany(joinColumns = { @JoinColumn(name = "user_id", unique = false) })

                public Map<User, Role> getUserRoleMap() {
          return userRoleMap;
           }
     } 

Basic requirement is to retrieve list of roles assigned to different users in a branch.

Problem facing: since one user can have multiple roles assigned to it, map will no work for user-role mapping data.

One solution could be Map>, but i doubt if i can use nested collection with hibernate.

Please help me out!

If question is not understandable or not in representable form please let me know.

回答1:

My suggestion would be to introduce a new concept in your domain-model RoleAssignment:

class RoleAssignment {
  private User user; 
  private Branch branch;
  private Role role;
}

Entities User, Branch and Role should have 1:N relationship with RoleAssignment. For eg:

class User { 
  private Set<RoleAssignment> roleAssignemnts;
}