Reputation: 8783
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):
Role
(R1) with a Privilege
entity (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:
entityManager.persist
and entityManager.merge
I have not tried (yet):
@JoinColumn( name = "PRIV_ID" )
on the mappingI'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.
Upvotes: 1
Views: 470
Reputation: 12367
OneToMany implies that privilege has backlink (via foreigh key ) to - also, it belongs to one and only one role, and can not belong to two. You need many-to-many to achieve your goal
Upvotes: 0
Reputation: 691655
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 privileges
collection.
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.
Upvotes: 1