Search code examples
javajpaeclipselinkjpa-2.1bulk-delete

What is the best way to bulk delete rows in JPA while also cascading the delete to child records


I'm trying to do bulk delete in my entities, and the best solution will be to go with CriteriaDelete. But CriteriaDelete does not cascade (at least not for me).

So, it seems like the only solution which I have is to do select first and delete each element separately. Which does not seems wrong to me.

Is anyone have a better idea of how to do bulk delete? Is it actually a better way?

If it helps I'm using EclipseLink 2.5.2.


Solution

  • The options are:

    1. use the cascade.Remove setting on the mapping, loading entities and calling em.remove on each
    2. Use bulk delete on the main entity and have the "ON DELETE CASCADE" database option set so that the database will cascade the delete for you. EclipseLink has a @CascadeOnDelete annotation that lets it know the "ON DELETE CASCADE" is set on a relationship, or to create it if using JPA for DDL generation: http://eclipse.org/eclipselink/documentation/2.5/jpa/extensions/a_cascadeondelete.htm
    3. Use multiple bulk deletes to remove children that might be referenced before removing the main entity. For example: "Delete FROM Child c where c.parent = (select p from Parent P where [delete-conditions])" and "Delete FROM Parent p where [delete-conditions]" See section 10.2.4 of http://docs.oracle.com/middleware/1212/toplink/OTLCG/queries.htm#OTLCG94370 for details.