Video in progress

Strong Middle 🐻 Hibernate and JPA

What SQL do Spring Data's `deleteAll()`, `deleteAllInBatch()` and `deleteByStatus()` run internally?

deleteAll() and the derived deleteBy... first load the entities and then send a separate DELETE for each one. Cascade and callbacks work, but it's slow. deleteAllInBatch() and @Modifying @Query("delete ...") delete with a single SQL statement, but bypass cascade, orphanRemoval and the persistence context.

📖 Answer

long deleteByStatus(Status status);            // SELECT + N DELETEs
void deleteAll();                              // SELECT * + N DELETEs
void deleteAllInBatch();                       // delete from orders
void deleteAllByIdInBatch(Iterable<Long> ids); // delete from orders where id in (...)

A derived deleteBy surprises a lot of people: from the name you expect one SQL statement, but the log shows first select ... where status = ? and then delete from orders where id = ? for each row. The reason is that Spring Data deletes through em.remove() so that @PreRemove, CascadeType.REMOVE and orphanRemoval work. For 100 thousand rows that takes minutes.

If you need a single SQL statement:

@Modifying
@Query("delete from Order o where o.status = :s")
int purge(@Param("s") Status s);

It's fast, but if there's a child table, you get an FK error, because cascade doesn't work here. Either delete the children yourself first, or the FK has on delete cascade. Also, entities already loaded in the context become "dead", so clearAutomatically = true is useful.

When I see deleteAllInBatch() in prod code, I always ask a question: a delete from orders with no condition is a dangerous method, even if it's meant for tests.

My choice goes like this: few records and there's domain logic (callbacks, cascade): the remove() route. A big cleanup: a bulk query, in batches if needed (a loop with limit).