Why does a Repository's delete method not have any return values?

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

In the implementation of the delete method, 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.

Upvotes: 17

Views: 32505

Answers (3)

Eklavya
Eklavya

Reputation: 18430

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
}

Upvotes: 18

Amir
Amir

Reputation: 1834

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);
}

Upvotes: 8

Felipe Mosso
Felipe Mosso

Reputation: 3927

Another option would be to follow the suggestion from this answer and check if the number of affected entities is 1 (in case of a deleteById method).

Upvotes: 0

Related Questions