Java QueryDsl - 集合表达式中的子查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21826773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:55:18  来源:igfitidea点击:

QueryDsl - subquery in collection expression

javaspringspring-dataquerydsl

提问by wiecia

I'm using spring-data-jpa and querydsl (3.2.3)
I have a scenario where I'm creating set of predicates based on user filer/input. All of these comes to BooleanExpression.

我正在使用 spring-data-jpa 和 querydsl (3.2.3)
我有一个场景,我正在根据用户文件管理器/输入创建一组谓词。所有这些都归结于BooleanExpression

My simplified model looks as following:

我的简化模型如下所示:

@Entity
public class Invoice {
    @ManyToOne
    private Supplier supplier;
}

@Entity
public class Supplier {
    private String number;
}

@Entity
public class Company {
    private String number;
    private boolean active
}

Now, what I'm struggling with is this query:

现在,我正在苦苦挣扎的是这个查询:

SELECT * FROM Invoice WHERE invoice.supplier.number in (SELECT number from Company where active=true)

So basically I need to subquery in CollectionExpressionlike format that will fetch all companies numbers and sets this into in() expression.

所以基本上我需要以CollectionExpression类似的格式进行子查询,该格式将获取所有公司编号并将其设置为 in() 表达式。

My spring-data repositories implements CustomQueryDslJpaRepositorywhich in turn extends JpaRepositoryand QueryDslPredicateExecutor.
I hope the answer to this is straightforward, but I'm quite new to querydsl and didn't find the solutions so far.

我的 spring-data 存储库实现了CustomQueryDslJpaRepository它依次扩展JpaRepositoryQueryDslPredicateExecutor.
我希望这个问题的答案很简单,但我对 querydsl 很陌生,到目前为止还没有找到解决方案。

采纳答案by Timo Westk?mper

Here is a variant of jaiwo99's answer in a more JPAesque form

这是 jaiwo99 的答案的变体,采用更 JPAesque 的形式

BooleanExpression exp = invoice.supplier.number.in(new JPASubQuery()
    .from(company)
    .where(company.active.isTrue())
    .list(company.nu??mber));

Feel free to merge this into the original answer.

随意将其合并到原始答案中。

回答by Jaiwo99

Try this:

尝试这个:

QInvoice invoice = QInvoice.invoice;
QCompany company = QCompany.company;

List<Invoice> list = new HibernateQuery(sessionFactory.getCurrentSession())
      .from(invoice).where(
      new HibernateSubQuery().from(invoice, company).where(
              invoice.supplier.number.eq(company.number).and(
              company.active.eq(true))).exists()).list(invoice);