java - Spring JPA 属性表达式通过列表中项目的交集查找

标签 java spring spring-data spring-data-jpa

如何使用属性表达式编写 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/

相关文章:

java - Spring Data JPA 在创建对象时保存多对多关系

spring - 是什么导致 Hibernate 选择上出现此 NullPointerException?

mysql - 用户 '' @'localhost' 的访问被拒绝(使用密码 : NO) spring-boot

java - 如何在 Firestore 中插入对象数组?

java - quarkus 2.1.4 - mvnw quarkus :dev not working on windows 10

Java根据文件名中的日期查找目录中的最新文件

java - Redis - 如何配置自定义转换

java - Spring-Data-JPA - 将一条记录插入数据库后无限递归

java - gvim/vim : launching from within Java program with parameters

java - spring 任意消息 TCP 套接字