JPA: DELETE WHERE does not delete children and throws an exception

后端 未结 5 1070
渐次进展
渐次进展 2020-12-08 14:42

I am trying to delete a large number of rows from MOTHER thanks to a JPQL query.

The Mother class is defined as follows:

@E         


        
5条回答
  •  离开以前
    2020-12-08 15:01

    DELETE (and INSERT) do not cascade via relationships in JPQL query. This is clearly spelled in specification:

    A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

    Luckily persist and removal via entity manager do (when there is cascade attribute defined).

    What you can do:

    • fetch all Mother entity instances that should be removed.
    • for each of them call EntityManager.remove().

    Code is something like this:

    String selectQuery = "SELECT m FROM Mother m WHERE some_condition";  
    List mothersToRemove = entityManager
        .createQuery(selectQuery)
        .getResultStream()
        .forEach(em::remove);
    

提交回复
热议问题