Eugen
Eugen

Reputation: 8783

JPA (with Hibernate) reatach existing entities in a @OneToMany -

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):

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:

I have not tried (yet):

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.

Upvotes: 1

Views: 470

Answers (2)

Konstantin Pribluda
Konstantin Pribluda

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

JB Nizet
JB Nizet

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

Related Questions