I have the following (simple) mapping:
@Entity
public class Role {
@OneToMany( fetch = FetchType.EAGER ) private Set< Privilege > privileges;
}
I want to do the following (simplified):
- I have created a
Role(R1) with aPrivilegeentity (P1) - I want to create another, new Role (R2) and give it the same privilege (P1)
So, when the new R2 is created, it’s Set of Privilege is also new (HashSet not PersistedSet) but it contains the existing P1; It seems that Hibernate is unable to recognise the fact that P1 already exists and properly persist the relation
I have already tried to following:
- save the new Role (R2) with both
entityManager.persistandentityManager.merge - add cascade = { CascadeType.ALL } to the mapping between Role and Privilege
- tried to preload the Privileges (so that the entities exist in the current session) before saving the new Role
I have not tried (yet):
- specifying the
@JoinColumn( name = "PRIV_ID" )on the mapping - doing more operations by hand (like first persisting the empty Role entity and them updating the Privileges) – last resort
I’m thinking that this is a pretty standard usecase, so perhaps I’m missing something that is preventing me to persist this association properly.
Any ideas?
Thanks.
If two roles may have the same privilege, then it’s not a OneToMany anymore, but a ManyToMany. So start by changing the mapping of the
privilegescollection.Then show us the code which adds P1 to the set of privileges of R2. I suspect that you’re creating a new Privilege instance, instead of getting P1 from the session.