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
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 roles = new HashSet();
...
}
@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 users = new HashSet();
...
}
Additional notes:
Set. It would be useful if the Set was a SetmappedBy attribute) to persist the association.