Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleteById vs delete in spring jpa

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

like image 862
TerryPhan Avatar asked May 09 '19 18:05

TerryPhan


People also ask

How do I delete a record using JPA?

To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.

How do I delete multiple records in JPA?

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.

How do I delete an entity in JPA?

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.

What is difference between save and saveAndFlush in JPA?

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.


1 Answers

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.

like image 100
ksak Avatar answered Sep 19 '22 04:09

ksak