You must remove the object from its parent list and parent from the object itself to the removal of the object.
An example (CMT in EJB) of one-to-many state to city:
public boolean delete(City city) {
City managedCity = entityManager.contains(city) ? city : entityManager.merge(city);
managedCity.getState().getCityList().remove(managedCity);
managedCity.setState(null);
entityManager.remove(managedCity);
return true;
}
The operator managedCity.setState(null);sets the parent of the object null. Since this is a managed entity, any changes made to the entity will go to the base database. Accordingly, an operator will be created UPDATE, and state_idin the database table it will be set to null.
UPDATE db.city SET state_id = ?, row_version = ? WHERE ((city_id = ?) AND (row_version = ?))
bind => [null, 2, 10, 1]
This is completely undesirable. In addition to issuing the addition UPDATE, it tries to set state_idthe database table to null, which will cause problems if the database constraint NOT NULLis enforced on the corresponding column in the database table.
How to correctly remove the parent object before deleting the entity itself or is it not even necessary to remove (set it to null) the parent element before deleting the object (this can cause problems in some cases. Therefore, the answer should be, No)?
source
share