delete() and deleteInBatch() both remove entities, but they differ in execution strategy -- delete() removes a single entity (or, when passed a collection, issues one DELETE statement per entity), while deleteInBatch() removes a whole collection of entities using a single, more efficient DELETE statement.
Key Points: • delete(entity) issues one SQL DELETE per call, and also triggers any relevant JPA lifecycle callbacks (like @PreRemove) for each entity. • deleteInBatch(entities) generates a single bulk DELETE ... WHERE id IN (...) style statement, dramatically reducing database round trips for large collections. • Because deleteInBatch() bypasses the normal per-entity removal lifecycle, entity callbacks and cascade behavior may not fire the same way they would with delete(). • deleteInBatch() is the better choice when deleting a large number of entities at once purely for performance, as long as you don't need per-entity lifecycle hooks to run.
Example: Deleting 5,000 expired session entities one at a time with delete() means 5,000 round trips to the database, while deleteAllInBatch()/deleteInBatch() collapses that into a single DELETE statement, which is dramatically faster for a bulk cleanup job.
Code Example:
// One DELETE statement per entity
List<Session> expired = sessionRepository.findByExpiredTrue();
sessionRepository.deleteAll(expired);
// Single bulk DELETE statement
sessionRepository.deleteInBatch(expired);Interview Tip: A concise interview answer is:
"delete() removes entities one at a time, issuing a separate SQL statement per entity and firing any lifecycle callbacks, while deleteInBatch() collapses a whole collection into a single bulk DELETE statement for much better performance. I use deleteInBatch() for large bulk cleanups where I don't need per-entity callbacks to fire, and delete() when I do."