Anand
Anand

Reputation: 1387

Hibernate Multiple Association Issue

I have 3 entities. User,Project and Role. A user can be assigned to multiple projects with some roles. A user GEORGE can have ADMIN role on PROJECT-A and MANAGER role on PROJECT-B. How can I map these entities using bi-directional association.

*The relation can be described in following way.

A USER can have many projects through a role.

A role can be assigned to 0 or more projects for a specific User.*

Is it possible with a JOIN-TABLE.

Upvotes: 0

Views: 574

Answers (2)

JB Nizet
JB Nizet

Reputation: 691635

You'll need to introduce a fourth entity (let's call it Right), which tells that a specific user has a specific role on a specific project. You will thus end with the following associations :

  • One User has Many Rights
  • One Role has Many Rights
  • One Project has Many Rights

The RIght entity will be mapped to a table having three foreign keys (to user, role and project), and the tuple (userId, projectId, roleId) should be unique.

You'll need to use dedicated queries (or Java methods) to find the roles of a user for a project :

public class User {
    // ...
    public Set<Role> getRolesForProject(Project project) {
        Set<Role> result = new HashSet<Role>();
        for (Right right : rights) {
            if (right.getProject().equals(project)) {
                result.add(right.getRole());
            }
        }
        return result;
    }
}

or, in HQL :

select role from Right right 
inner join right.role role 
where right.user = :user 
and right.project = :project

Upvotes: 1

chzbrgla
chzbrgla

Reputation: 5188

If the user can not have multiple roles within a project, just map @ManyToOne Projects to your User and have the Role relation reside in your Project class.

class User {
     @OneToMany (mappedBy = "projects")
     List<Project> projects;
     [...]
}

class Project {
     @ManyToOne
     User user;
     Role userRole;
     [...]
}

This does however neglect the possibility to have multiple users assigned to one project, which you didn't state but i believe should be a possibility.

Just look up Hibernate Annotations an Bi-directional (BI-WINNING!) on google or your favorite search engine.

Didn't really go into detail here, seeing that OP only has 29% accept rate..

cheers

Upvotes: 1

Related Questions