简体   繁体   中英

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM