我有一个仓库
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);
或等效的 based on
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);
}
关于Spring JPA 存储库查找所有不存在的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58989498/