I got a problem with a many to many association in my persistence layer. My scenario is the following:
A user can has several roles and a role can have several user
When dealing with a bidirectional many-to-many association you have to maintain both ends of the association. In your case, you have to add the user to the role as well. Adding the role to the user isn't sufficient to establish a bidirectional association as you can read in book Java Persistance with Hibernate:
As always, a bidirectional association (no matter of what multiplicity) requires that you set both ends of the association.
The problem probably comes from the fact that you mapped the same bidirectional association twice. If you tell Hibernate twice about the same join table or join column, there is a problem. In a bidirectional association, one of the ends of the association must map the association, and the other one must tell Hibernate that it's the inverse of the other end, using the mappedBy
attribute.
Since a many-to-many is completely symmetric, choose one of the end to be the owner (i.e. the end which maps the association, and thus have the @JoinTable
annotation). The other side is just the inverse, and thus doesn't have a @JoinTable
annotation, but has a mappedBy
attribute.
Example:
@Entity
@Table
public class User extends BusinessObject {
...
// This end is the owner of the association
@ManyToMany
@JoinTable(name= "user_role",
joinColumns = {@JoinColumn(name="user_id")},
inverseJoinColumns = {@JoinColumn(name="role_id")})
private Set<Role> roles = new HashSet<Role>();
...
}
@Entity
@Table
public class Role extends BusinessObject {
...
// This end is not the owner. It's the inverse of the User.roles association
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<User>();
...
}
Additional notes:
Set
. It would be useful if the Set was a Set<SomeInterface>
mappedBy
attribute) to persist the association.