Home > Blockchain >  How to get number of rows deleted using deleteAll()?
How to get number of rows deleted using deleteAll()?

Time:07-23

I want to get number of deleted rows with deleteAll() using SpringRepository. It is pretty simple to obtain this if I write my own function, just like in this thread. However, I want to override deleteAll() method. The following code doesn't work:

public interface CalculationInfoRepository extends MongoRepository<CalculationInfo, Long> {
  @Override
  @Modifying
  int deleteAll(Iterable<? extends CalculationInfo> entities);
}

because I get

The return type is incompatible with CrudRepository<CalculationInfo,Long>.deleteAll(Iterable<? extends CalculationInfo>)

How should I do it?

CodePudding user response:

The CrudRepository#deleteAll returns void by definition, you cannot override a return type. But you can create your own method, e.g., int deleteAllAndGetCount.

https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html

CodePudding user response:

You can achieve this using org.springframework.data.jpa.repository.Query annotation:

public interface CalculationInfoRepository extends MongoRepository<CalculationInfo, String> {
    @Modifying
    @Query(value = "{id : {$in: :#{#ids}}}", delete = true)
    int deleteCalculationInfos(@Param("ids") Iterable<String> ids);
}

It will delete rows by ids with String type and return number of deleted rows.

  • Related