如何使用属性表达式编写 JPA 存储库方法来检查列表中是否存在多个项目或这些项目的属性?我可以在列表中查找单个项目,查看下面的邮政编码,但我正在尝试编写一种方法来检查多个邮政编码,结果集中的每个人的地址列表中都有两个邮政编码。
@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
// Works
Set<Person> findAllByAddresses_ZipCode(String zip);
// Doesn't work - does not return expected results
Set<Person> findAllByAddresses_ZipCode_And_Addresses_ZipCode(String zip1, String zip2);
}
我目前的技巧是为 2 个邮政编码获取两组,然后找到这两组的交集:
public @ResponseBody
Iterable<Person> personsWithBothZipCodes(@PathVariable("zip1") String zip1,
@PathVariable("zip2") String zip2) {
Set<Person> a = personRepository.findAllByAddresses_ZipCode(zip1);
Set<Person> b = personRepository.findAllByAddresses_ZipCode(zip2);
// Only return results that contain both zip1 and zip2.
a.retainAll(b);
return a;
}
实体看起来像这样:
@Entity
public class Person
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// zipcode is a String property on an Address.
@OneToMany(targetEntity = com.data.Address.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Address> addresses = new ArrayList<Address>();
...
}
有没有办法把它写成方法头的一部分? Relevant docs
最佳答案
是的,只需将单词 In
添加到您的查询中
Set<Person> findAllByAddresses_ZipCodeIn(Set<String> zip);
然后在你的 Controller 中你可以做这样的事情:
public @ResponseBody Iterable<Person> personsWithBothZipCodes(@PathVariable("zip1") String zip1, @PathVariable("zip2") String zip2) {
Set<String> zipSet = new HashSet<>();
zipSet.add(zip1);
zipSet.add(zip2);
Set<Person> a = personRepository.findAllByAddresses_ZipCodeIn(zipSet);
return a;
}
不知道这样行不行,可以试试
Set<Person> findAllByAddresses_ZipCodeInAndZipCodeIn(Set<String> zip1, Set<String> zip2);
public @ResponseBody Iterable<Person> personsWithBothZipCodes(@PathVariable("zip1") String zip1, @PathVariable("zip2") String zip2) {
Set<String> zipSet1 = new HashSet<>();
zipSet1.add(zip1);
Set<String> zipSet2 = new HashSet<>();
zipSet2.add(zip2);
Set<Person> a = personRepository.findAllByAddresses_ZipCodeInAndZipCodeIn(zipSet1, zipSet2);
return a;
}
关于java - Spring JPA 属性表达式通过列表中项目的交集查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48774564/