Mikael S.
Mikael S.

Reputation: 1015

JPA - delete a child from OneToMany relationship

In a @OneToMany relationship if I want to remove a child, do I need to explicitly delete that child from parent's collection as well or just deleting the child will suffice?

For instance, Person and Phone. Each person has many phone numbers. If I want to delete one phone number from a person is this enough:

EntityManager.remove(phone);

Or I need to to this beforehand:

Person.getPhone().remove(phone); 

Not to mention, the CascadeType is set to MERGE.

Upvotes: 9

Views: 12850

Answers (2)

Balázs Németh
Balázs Németh

Reputation: 6637

You need to remove the Phone explicitly from the phones collection, it's not enough to remove it with the EntityManager.

From the other side, it might be sufficient to use orphanRemoval, so if you remove an entity from a collection, it gets automatically deleted. Something like:

@OneToMany(mappedBy="person", orphanRemoval="true")
private List<Phone> phones;

See also: http://docs.oracle.com/cd/E19798-01/821-1841/giqxy/index.html

Cascade.REMOVE only removes the child entity if the parent entity is removed as well. Cascase.MERGE has nothing to do with this problem.

Upvotes: 11

Gimby
Gimby

Reputation: 5299

Not sure if MERGE is enough to get entities deleted cascaded, you will probably have to also define DELETE cascading and depending on how the data is mapped (with or without a secondary table in between) it might even be necessary to apply orphan removal too.

If you don't apply cascading for deletion but rather use a JPA query or an entityManager.remove(), then it is certainly a good idea to manually evict it from the oneToMany collection as well. The reason is simple: you may manually remove it from the database, but that doesn't mean it automagically gets removed from the collection too so for the lifetime of the parent entity, it will still be referencing an entity which is not supposed to exist anymore. Things get weird when you then also accidentally change the state of said entity.

Upvotes: 3

Related Questions