Relationship with Enumerated Type in Java
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 E开发者_开发百科numerated Type.
Have you had a look at the EnumSet class? This can store multiple Enum instances in a collection you can call contains()
on
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.
We usually create subclasses EnumUserType and then specify this class in the mapping file.
精彩评论