【问题标题】:How in Querydsl for Spring Data JPA do I find those entitities that have at least one child satisfying several conditions?我如何在 Spring Data JPA 的 Querydsl 中找到那些至少有一个孩子满足多个条件的实体?
【发布时间】:2020-06-26 08:41:31
【问题描述】:

我的模型中有以下关系:

我正在尝试使用 Spring Data JPA 中的 Querydsl 功能来查找相关学生在给定日期范围内在给定住宅中租赁的所有活动。我尝试了以下方法来返回适当的BooleanExpression,该BooleanExpression可以与其他人结合并提供给EngagementRepository.findAll()

public BooleanExpression inResidence(Residence residence, LocalDate startDate, LocalDate endDate) {
    final QTenancy tenancies = QEngagement.engagement.student.tenancies.any();
    return tenancies.residence.eq(residence)
        .and(tenancies.startDate.loe(endDate))
        .and(tenancies.endDate.goe(startDate));
}

但是,生成的 SQL 包含三个条件中的每一个的独立 EXISTS 子查询 - 居住地、开始日期和结束日期;也就是说,就目前而言,当我所追求的是符合所有三个条件的合格租赁时,每个条件都可以通过不同的租赁来满足。我意识到我可能误解了any() 的目的,并怀疑我需要使用 Querydsl 的子查询,但我不太确定如何使用,特别是因为我发现的一些示例适用于版本 3,而且情况似乎已经改变在第 4 版中。

【问题讨论】:

    标签: spring-data-jpa querydsl


    【解决方案1】:

    这是我设法在 Querydsl 4 中使用子查询的方法。生成的 SQL 只有一个 EXISTS 子查询来测试所有三个条件。

    public BooleanExpression inResidence(Residence residence, LocalDate startDate, LocalDate endDate) {
        final QTenancy tenancy = QTenancy.tenancy;
        return QEngagement.engagement.student.tenancies.any().in(
            JPAExpressions.selectFrom(tenancy).where(
                tenancy.residence.eq(residence)
                    .and(tenancy.startDate.loe(endDate))
                    .and(tenancy.endDate.goe(startDate))
            )
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2012-04-22
      • 2021-10-12
      • 1970-01-01
      相关资源
      最近更新 更多