views:

146

answers:

3

I'm trying to create a many-to-many relationship between two types of which one is an Enumerated type. Lets say the first model is User and the second model is Role. A user can have many roles and a role can belong to many users.

I'd like to be able to write simple code like:

if (user.getRoles().contains(Role.ADMIN)) {
  //do something
}

Does anyone know if this is possible? I've seen that there is an @Enumerated Hibernate annotation but this doesn't look to be of use to me.

I've currently implemented a solution by created a model for a link table but this is very messy. Any help much appreciated.

-gearoid

UPDATE: Can someone specify how to persist an EnumSet on a model? The info above still stands, I wish to create a ManyToMany relationship with an Enumerated Type.

+2  A: 

Have you had a look at the EnumSet class? This can store multiple Enum instances in a collection you can call contains() on

thecoop
Thanks - I dont suppose you have any example of where the EnumSet is used in a many-to-many relationship?
Gearóid
Can't you add an EnumSet instance to the User and Role enums, holding instances of the other type?
thecoop
Well, the enumerated type is only on one side of the relationship. Lets just say I simply had an EnumSet on the User model (forget about the Role model for now) - how would this get persisted?I've tried to implement it but am getting an error saying that the "Data too long for column" when I try to save...
Gearóid
A: 

We usually create subclasses EnumUserType and then specify this class in the mapping file.

bertolami
A: 

I think I have found a good solution to the problem. If I keep my Enumerated Type as something simple such as:

public enum Role implements Serializable{

    USER, MODERATOR, ADMIN;

}

And then on my User model I create a Set of Roles with the @CollectionOfElements so it looks something like this:

  @CollectionOfElements(fetch = FetchType.EAGER)
  public Set<Role> getRoles() {
   return roles;
  }

  public void setRoles(Set<Role> roles) {
   this.roles = roles;
  }

Hibernate seems to create a table for this relationship (called user_roles) which works as I'd like (A regular manyToMany relationship).

Hope this helps someone.

-gearoid.

Gearóid