Following scenario:
I have
user object:
...
@Column(name = "TITLE")
private String title;
@NotNull
@NotEmpty
@Column(name = "STREET_ADRESS")
private String streetAdress;
@NotNull
@NotEmpty
@Column(name = "CITY")
private String city;
…
@OneToMany(fetch = FetchType.EAGER)
@NotNull
@NotEmpty
protected Set<Role> roles = new HashSet<Role>();
Role roleDaoById = roleService.getRoleByName(RoleName.User.toString());
Set<Role> roles = new HashSet<Role>();
roles.add(roleDaoById);
member.setRoles(roles);
member.setSuspend(false);
member.setPlayer(true);
memberService.addMember(member);
My problem is that roles are already available in the database. That’s why i load them via roleService.
I call memberService.addMember and this calls my dao with em.persist(member). But this call does save the role again and i get a duplicate key error for the role object.
I only want to save the member and then make the join table entry for the role.
What can i do?
Your relation User – Role is Many-To-Many (one user has multiple roles, multiple users can have the same role), but you annotated it with One-To-Many.