【问题标题】:Subsequent query execution in JPAJPA 中的后续查询执行
【发布时间】:2021-04-01 12:15:19
【问题描述】:

假设在 Spring Boot 中有一个名为 Person 的类,其结构如下

@Entity
class Person {
    Long id;
    String name;
    @OneToMany
    Set<PhoneNumber> phoneNumbers;
}

Person 由一组电话号码组成。

@Entity
class PhoneNumber {
    Long id;
    @ManyToOne
    @JoinByColumn("person_id")
    Person person;
    String category;
    String mobileNumber;
    String phoneNumber;
}

PhoneNumber是一个由以上字段组成的类,其中category代表mobilephone等。

class PersonRepository extends JPARepository<Person, Long> {
     Person findById(Long id);
}

所以,每当我想用一些id 获取Person 详细信息时,我将调用上述方法findById,然后它应该获取Person 详细信息以及phoneNumbers,其category 是@987654334 @。

该方法应该是每当它在内部对findById 方法执行查询时,它应该执行后续查询以获取类别为mobilePhoneNumber。 有什么办法可以像上面提到的那样得到它,或者有没有其他方法可以实现它?请告诉我。

PS:如果我的提问方式有任何问题或错误,请在下方评论。它会帮助我。

【问题讨论】:

  • 我不太确定我是否理解您的问题。您想获取具有给定 id 的人的手机号码吗?那么您是否希望查询先返回此人,然后获取手机号码?或者您是否希望查询仅在至少有一个手机号码时才返回一个人?还是您希望查询在一个请求中返回此人和所有关联的手机号码?
  • 我希望查询返回person 以及category 是移动电话的所有关联电话号码。
  • 我认为这就是您正在寻找的 stackoverflow.com/q/66435595/2683501 但这非常危险。也许你应该反过来做,然后让 PhoneNumber 表给我每个带有 personcategory 的条目
  • 好吧,您不能过滤 Person 中的集合,因为这可能会破坏 JPA,但您可以通过连接(如 SELECT p, n FROM Person p JOIN p.phoneNumbers n ...)加载人和数字的笛卡尔积。但是为什么不加载所有电话号码并在代码中过滤(只是不要更改集合本身)?还是在单独的查询中加载数字?
  • @Thomas,即使我想在代码中过滤它,但我只是想知道是否有任何方法可以通过使用 JPA 来做到这一点

标签: java spring-boot hibernate jpa spring-data-jpa


【解决方案1】:

你可以得到它。参考这个:

回购:

class PersonRepository extends JPARepository<Person, Long>,JpaSpecificationExecutor<Post> {
     Person findById(Long id);
}
    public static Specification<Person> search(Long id) {
        return ((root, criteriaQuery, criteriaBuilder) -> {
            criteriaQuery.distinct(true);
            return criteriaBuilder.and(
                    criteriaBuilder.equal(root.get("id"), id),
                    criteriaBuilder.equal(root.join("phone_number").get("category"), "mobile")
           );
        });
    }
personRepo.findAll(search(10));

【讨论】:

【解决方案2】:

你可以试试这个方法-

// method in Person entity class
public static List<Person> findByIdMobile(long id, String category) {
  return find("id = ?1 and  phoneNumbers.category = ?2", id, category).list();
}

// can use this as
List<Person> mobilePersons = Person.findByIdMobile(1234,"mobile");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多