首先,您的存储库应该扩展JpaRepository<Person, Long>而不是JpaRepository<Person, String >,因为您的实体的 id 类型是Long.
In关键字NotIn可以帮助您实现目标。请在本文档中查看它们:查询创建 - Spring Data JPA - 参考文档
我稍微修改了你的代码,它对我有用。
存储库类:
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> findByIdIn(Collection<Long> ids);
}
和示例片段:
@Component
public class Bootstrap implements CommandLineRunner {
@Autowired
private PersonRepository repository;
@Override
public void run(String... args) throws Exception {
savePersons();
testFindMethod();
}
private void savePersons() {
Person person1 = Person.builder().id(1L).name("Name 1").build();
Person person2 = Person.builder().id(2L).name("Name 2").build();
Person person3 = Person.builder().id(3L).name("Name 3").build();
Person person4 = Person.builder().id(4L).name("Name 4").build();
repository.save(person1);
repository.save(person2);
repository.save(person3);
repository.save(person4);
}
private void testFindMethod() {
List<Long> toFind = new ArrayList<>();
toFind.add(1L);
toFind.add(2L);
toFind.add(3L);
checkIfAllPersonsExist(toFind);
toFind.add(7L);
checkIfAllPersonsExist(toFind);
}
void checkIfAllPersonsExist(List<Long> personIds) {
List<Person> persons = repository.findByIdIn(personIds);
if (personIds.size() != persons.size()) {
System.out.println("Sizes are different");
} else {
System.out.println("Sizes are same!");
}
}
}
这是控制台输出:
Sizes are same!
Sizes are different
我希望这能帮到您。