Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not delete method of spring data (JPA) have any return values?

I have used a delete method of Spring Data JPA in the service layer, but I wonder why neither the deleteById method nor delete method has any return values.

If we inspect the implementation of the delete method carefully, there is an if statement that when the entity to be deleted doesn't exist returns nothing.

public void delete(T entity) {

    Assert.notNull(entity, "Entity must not be null!");

    if (entityInformation.isNew(entity)) {
        return;
    }

    Class<?> type = ProxyUtils.getUserClass(entity);

    T existing = (T) em.find(type, entityInformation.getId(entity));

    // if the entity to be deleted doesn't exist, delete is a NOOP
    if (existing == null) {
        return;
    }

    em.remove(em.contains(entity) ? entity : em.merge(entity));
}

Personally, I think returning a Boolean value could be an adequate approach in this case because the controller layer will know about the deletion status, and the view layer can be provided with the far more reliable alert message.

like image 839
Elyas Hadizadeh Avatar asked Feb 03 '23 15:02

Elyas Hadizadeh


2 Answers

Spring Data JPA design some build-in methods that way they think and give us the option to use the other way also. You can easily get deleted records and their count using derived delete query supported By Spring Data JPA (Reference)

@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    Fruit deleteById(Long id); // To get deleted record
}
@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    Long deleteById(Long id);  // To get deleted record count
}
like image 165
Eklavya Avatar answered Feb 06 '23 05:02

Eklavya


use @Modifying and @Query ant it will return number of deleted rows.

@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    @Modifying
    @Query(value = "DELETE FROM Fruit f where f.id = ?1")
    int costumDeleteById(Long id);
}
like image 39
Amir Avatar answered Feb 06 '23 04:02

Amir