简体   繁体   中英

Handling multi-layer many-to-many relationship in Hibernate

I have three entities:

  1. User
  2. Role, and
  3. Right

Each User has several Roles , and each Role has several Right . The class definition is like:

@Entity
@Table(name="...")
public class User {
    ...        
    @ManyToMany
    @JoinTable(...)
    private List<Role> UserRoles; 
}
...
@Entity
@Table(name="...")
public class Role{
    ...        
    @ManyToMany
    @JoinTable(...)
    private List<Right> RoleRights; 
}

I want to do the following two tasks:

  1. Show the Right for each User.
  2. Search Users by their Right.

Currently I've implemented (1) by the following:

// some method in the data access layer
public List<User> GetUser(){
    ...
    userList = (List<User>) someHibernateCriteria.list();
    if(userList != null && userList.size() > 0)
    {
        for(User user : userList)
        {
            Hibernate.initialize(user.getUserRoles());
            for(Role role : user.getUserRoles())
            {
                Hibernate.initialize(role.getRoleRights());
            }
        }
    }

    return userList;
}
...

Display code for jsp , looping the userList and putting each user in a html table row

<td>
    ${user.stringDescription}
</td>
<td>
    <ul>
    <c:forEach items="${user.userRoles}" var="role">
        <c:forEach items="${role.roleRights}" var="right">
            <li>${right.stringDescription}</li>
        </c:forEach>
    </c:forEach>
    </ul>
</td>

And I do (2) similarly too, ie populate the intermediate List of Role for getting the relation between User and Right. I wonder if this is a good practice or if there is a more efficient way to do the tasks.

是的,Spring Security中已经实现了逻辑

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