An application wants to utilize side effects of cascading entity manager operations to related entities.
Which statement is correct?
A.
The persist operation is always cascaded to related entitles for one-to one and one-to-many relationships.
B.
To minimize the effect of the remove operation applied to an entity participating in a many-to-many relationship the remove operation should hecascadeto entities on both sides of the relationship.
C.
The persist operation applied to a new entity x is cascaded to entities referenced by x if the relationship from x to these other entities is annotated with the cascade=PERSIST or cascade=ALL annotation element value.
D.
The remove operation applied to a removed entity x is cascaded to entities referenced by x of the relationship from x to these other entities is annotated with the cascade = REMOVE of cascade = ALL annotation element value.
Explanation:
http://stackoverflow.com/questions/4748426/cannot-remove-entity-which-is-target-of-onetoone-relation(answer 1)
http://stackoverflow.com/questions/4748426/cannot-remove-entity-which-is-target-of-onetoone-relation
You need to remove the association between parent and child first, otherwise Hibernate tries to persist the child again due to cascade = ALL:
EntityChild c = parent.getChild();
parent.setChild(null);
em.remove(c);
em.flush();
JPA 2.0 specification (3.2.2 Persisting an Entity Instance):
The persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element
value or specified with the equivalent XML descriptor element.
According to the JPA specification, correct answer is C.
Similar explanation you can also found on the following link:
http://www.objectdb.com/java/jpa/persistence/update
On commit the persist operation can be cascaded from all the entity objects that have to be stored in the database, including from all the modified entity objects. Therefore, entity objects that are referenced from modified entity objects by fields that are marked with CascadeType.PERSIST or CascadeType.ALL are also persisted.