spring - Spring JPA 存储库找到所有不存在的
问题描述
我有一个存储库
public interface PersonRepository extends JpaRepository<Person, Long> {}
实体看起来像这样:
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Person {
@Id
private Long id;
@NotBlank
private String name;
}
我想要一个方法来检查数据库表中是否存在所有“人员”,这是我目前所拥有的:
void checkIfAllPersonsExist(List<Long> personIds) {
var persons = personRepository.findAllById(personIds);
if (personIds.size() != persons.size()) {
personIds.removeAll(persons.stream().map(Persons::getId).collect(toList()));
throw new NotFoundException("Persons with id's [id:%s] does not exist", personIds);
}
}
我想知道 Spring JPA Repository 是否可以提供更优雅的东西?像返回不存在的 id 的特定命名查询一样?
解决方案
如果您只想知道有些 id 不存在,您可以计算它们
@Query("select COUNT(p.id) from Person p where p.id in :ids")
Long countIds(List<Long> ids);
或等效基于
long countByIdIn(Collection<Long> ids);
或返回存在的 id 列表
@Query("select p.id from Person p where p.id in :ids")
List<Long> getExistenIds(List<Long> ids);
然后过滤掉你需要的东西。
personIds.removeAll(personRepository.getExistenIds(personIds));
if (!personIds.isEmpty()) {
throw new NotFoundException("Persons with id's [id:%s] does not exist", personIds);
}