为什么spring数据(JPA)的delete方法没有任何返回值?

Ely*_*deh 6 java spring spring-data-jpa

Spring Data JPA在服务层使用了一个delete方法,但是不知道为什么这个deleteById方法和delete方法都没有返回值。

如果我们仔细检查 delete 方法的实现,有一个if 语句,当要删除的实体不存在时,它不返回任何内容。

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));
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我认为Boolean在这种情况下返回一个值可能是一种合适的方法,因为控制器层将知道删除状态,并且可以为视图层提供更可靠的警报消息。

Ekl*_*vya 8

Spring Data JPA 按照他们的想法设计了一些内置方法,并为我们提供了使用其他方式的选项。您可以使用 Spring Data JPA 支持的派生删除查询轻松获取已删除的记录及其计数(参考

@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    Fruit deleteById(Long id); // To get deleted record
    Long deleteById(Long id);  // To get deleted record count
}
Run Code Online (Sandbox Code Playgroud)

  • 返回类型与 CrudRepository&lt;TestoEntity,Long&gt;.deleteById(Long) 不兼容:不起作用 (6认同)

Ami*_*mir 6

使用@Modifyingant@Query它将返回已删除的行数。

@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    @Modifying
    @Query(value = "DELETE FROM Fruit f where f.id = ?1")
    int costumDeleteById(Long id);
}
Run Code Online (Sandbox Code Playgroud)