Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA - delete a child from OneToMany relationship

Tags:

java

jpa

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.

like image 404
Mikael S. Avatar asked Feb 07 '14 10:02

Mikael S.


Video Answer


2 Answers

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.

like image 86
Balázs Németh Avatar answered Oct 22 '22 12:10

Balázs Németh


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.

like image 38
Gimby Avatar answered Oct 22 '22 14:10

Gimby