What is the difference between delete(...)
and deleteInBatch(...)
methods in JpaRepostory in Spring ? The second one "deletes items in one SQL statement", but what does it mean from the application/database perspective ? Why exists two different methods with the similar results and when it is better to use one or other ?
EDIT: The same applies also for deleteAll()
and deleteAllInBatch()
...
void deleteInBatch(Iterable<T> entities) Deletes the given entities in a batch which means it will create a single Query. So the "delete[All]InBatch" methods will use a JPA Batch delete, like "DELETE FROM table [WHERE ...]".
First of all you need to create a jpa query method that brings all records belong to id. After that you can do deleteAll() operation on List.
To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.
The answers here are not complete!
First off, let's check the documentation!
void deleteInBatch(Iterable<T> entities) Deletes the given entities in a batch which means it will create a single Query.
So the "delete[All]InBatch" methods will use a JPA Batch delete, like "DELETE FROM table [WHERE ...]". That may be WAY more efficient, but it has some caveats:
That's because JPA will issue a bulk DELETE statement to the database, bypassing the cache etc. and thus can't know which entities were affected.
See Hibernate Docs
The actual code in Spring Data JPA
And while I can't find a specific article here, I'd recommend everything Vlad Mihalcea has written, to gain a deeper understanding of JPA.
TLDR: The "inBatch" methods use bulk DELETE statements, which can be drastically faster, but have some caveats bc. they bypass the JPA cache. You should really know how they work and when to use them to benefit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With