Video in progress
Why is a derived delete method like deleteByStatus so slow?
A derived delete first SELECTs all the matching entities into memory, then calls em.remove() for each: N DELETE queries plus cascades. For many rows you should write a single bulk DELETE with @Modifying @Query("delete ...").
📖 Answer
@Transactional
long deleteByStatus(Status status); // if there are 200 thousand rows...
Roughly what happens inside this method:
select * from orders where status = 'EXPIRED'; -- 200,000 rows into memory
delete from orders where id = ?; -- 200,000 times
Why does Spring Data do this? To preserve JPA semantics: @PreRemove callbacks, cascade = REMOVE and orphanRemoval have to work. On a small set that's right, but in a nightly cleanup job it's catastrophic: memory fills up, the transaction stays open for a long time, and locks are held.
For a large volume:
@Modifying
@Query("delete from Order o where o.status = :s and o.createdAt < :before")
int purge(@Param("s") Status s, @Param("before") Instant before);
That's a single SQL statement. But now you're responsible for:
- cascades don't work: you delete the related tables first yourself (or use
ON DELETE CASCADEin the database); - entity listeners and auditing don't run;
- deleting a huge number of rows at once also fills up locks and the WAL/undo log, so deleting in portions is better (for example 5000 ids at a time, in separate transactions).
The same issue applies to the difference between deleteAll() and deleteAllInBatch(): the first deletes one by one, the second with a single query.
Sign up to mark studied questions and save your progress.