deleteById vs delete in Spring Data JPA
Fast recall
Quick revision
Core answer
Whether you know deleteById does a hidden SELECT first (for cascades/callbacks) and the differing exceptions on missing targets
Assuming deleteById is cheaper because it takes only an id, missing the hidden SELECT it performs
Explain that the load enables cascade deletes and @PreRemove, use delete() when the entity is already loaded, and deleteAllInBatch() for bulk
Interview-ready guide
Interview answer
Use deleteById when the input is an identifier and delete when code already has the entity. Current SimpleJpaRepository implements deleteById through findById(...).ifPresent(delete), so absence is not an EmptyResultDataAccessException contract. delete checks entity state: a new entity can be ignored, a managed one can be removed directly, and a detached one may be found or merged as part of removal. SQL counts are not API guarantees. For large set-based deletion, bulk methods avoid per-entity work but also bypass normal entity lifecycle handling and may require clearing the persistence context.
deleteById vs delete in Spring Data JPA
Direct Answer
deleteById accepts an identifier; current Spring Data JPA looks up that entity and deletes it when present, while a missing id is silently ignored. delete accepts an entity and uses its state and identifier to perform removal. Neither method promises 'two queries versus one' because provider state, callbacks, cascades, and batching affect the SQL.
Common Mistakes & Pitfalls
- Thinking
deleteById()is cheaper — it does a hidden SELECT first; if you already have the entity, preferdelete(). - Not handling
EmptyResultDataAccessException— deleting a missing id throws; map it to a 404 instead of a 500. delete()on a detached/null entity — null throwsIllegalArgumentException; ensure the entity is managed.deleteAll()for huge sets — it loads each entity; usedeleteAllInBatch()for one SQL statement.
Check your understanding
Answer these without looking back at the article.
- Why does deleteById do a SELECT before DELETE?
- What is the difference between deleteAll() and deleteAllInBatch()?
- How do you efficiently delete many records in Spring Data JPA?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.