I have a question about methods deleteById and delete in spring-data. what is the difference between these methods? When should I use delete/deleteById? I search google for one day but i have no answer for it
To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.
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.
In JPA, to delete an entity, the entity itself must be managed, meaning that it is present in the persistence context. This means that the calling application should have already loaded or accessed the entity and is now issuing a command to remove it.
The saveAndFlush() Method Unlike save(), the saveAndFlush() method flushes the data immediately during the execution. This method belongs to the JpaRepository interface of Spring Data JPA.
The method deleteById
will throw an EmptyResultDataAccessException
if the supplied id
does not exist, whereas the method delete
will silently return if the supplied entity
hasn't been persisted yet, or for whatever reason it cannot be found by the EntityManager
.
Also, as @manish noted in their comment, the method deleteById
actually calls the delete
method internally if the findById
method is able to find an entity.
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