我在服务层中使用了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));
}
就我个人而言,我认为返回Boolean
值在这种情况下可能是一种适当的方法,因为控制器层将知道删除状态,而视图层可以获得更可靠的警报消息。
发布于 2020-04-06 13:12:37
设计了一些他们认为的内置方法,并给了我们使用另一种方式的选择。使用Spring (参考文献)支持的派生删除查询,您可以轻松地获得已删除的记录及其计数
@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
}
发布于 2022-02-21 00:09:21
使用@Modifying
和@Query
ant,它将返回已删除的行数。
@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
@Modifying
@Query(value = "DELETE FROM Fruit f where f.id = ?1")
int costumDeleteById(Long id);
}
发布于 2021-03-27 15:38:51
另一种选择是遵循这个答案的建议,检查受影响实体的数量是否为1(在deleteById
方法的情况下)。
https://stackoverflow.com/questions/61060324
复制相似问题