I have a many to many User <-> Roles relation. The User entity looks like this:
@Entity
@Table(name = "user",
uniqueConstraints = {@UniqueConstraint(columnNames = {"username", "email"})})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<>();
}
And the Roles entity is the following:
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = true, nullable = false)
private Long id;
@Enumerated(EnumType.STRING)
@Column(length = 60, name = "roleName", updatable = true, nullable = false)
private RoleName roleName;
}
Everything works fine, except one thing. When I insert two users with the same role the roles table getting two records with the same role, but different IDs.
The question is, can I eliminate this behavior? Ideally the ROLES table should not contain duplicated roles.
Any advice would be appreciated. :)