简体   繁体   English

如何使用Querydsl构造涉及多个表的复杂谓词?

[英]How to use Querydsl to construct complex predicate that involves multiple tables?

I am trying to utilize Querydsl to fetch some results from a table.我正在尝试利用 Querydsl 从表中获取一些结果。 So far, this is what I have tried -到目前为止,这是我尝试过的 -

Assume there are 5 entities named T1..T5.假设有 5 个名为 T1..T5 的实体。 And I am trying to do this SQL query in Querydsl -我正在尝试在 Querydsl 中执行此 SQL 查询 -

SELECT T1.*
FROM T1,T2,T3,T4,T5
WHERE T1.A=T2.A
AND T2.B=T5.B
AND T4.C=T2.C
AND T1.B=1234;

I tried the following, but the Hibernate query keeps running, and does not seem to end.我尝试了以下操作,但 Hibernate 查询继续运行,并且似乎没有结束。

booleanBuilder.and(JPAExpressions.select(qT1).from(qT1,qT2,qT3,qT4,qT5)
.where(
    qT1.a.eq(qT2.a)
    .and(qT1.a.eq(qT2.a))
    ... // and so on
    .exists());

I am using the Repository that extends QuerydslPredicateExecutor and using findAll to execute this.我正在使用扩展QuerydslPredicateExecutor的存储库并使用findAll来执行它。 The problem is that the query takes forever to run.问题是查询需要永远运行。 And I am interested only in the first result that may appear.我只对可能出现的第一个结果感兴趣。 So, where am I going wrong that is making the query execute forever?那么,我哪里出错了,导致查询永远执行?

Edit: I opted to use the JPAQuery instead.编辑:我选择使用 JPAQuery 代替。 And of course, the Hibernate query generated is the same.当然,生成的 Hibernate 查询也是一样的。 Here is my JPAQuery.这是我的 JPAQuery。

JPQLQuery jpqlQuery = new JPAQuery(entityManager);
        jpqlQuery.select(qT1).from(qT1, qT2, qT3, qT4, qT5).where(booleanBuilder);
        return jpqlQuery.fetch();

How do I incorporate the limit in the above JPAQuery so that only the first result is fetched?如何在上述JPAQuery中合并limit ,以便只获取第一个结果?

The complexity is not in the predicate or in QueryDSL, but in the fact that you're executing it in a subquery that has to be executed for every row in the result.复杂性不在于谓词或 QueryDSL,而在于您在子查询中执行它,该子查询必须为结果中的每一行执行。 Depending on the total result set size, this may become increasingly difficult to compute.根据总的结果集大小,这可能会变得越来越难以计算。 It is however equally complex among QueryDSL, Hibernates HQL, JPA's JPQL or your databases SQL.然而,它在 QueryDSL、Hibernates HQL、JPA 的 JPQL 或您的数据库 SQL 中同样复杂。 So the SQL you're trying to generate, will be just as slow.因此,您尝试生成的 SQL 将同样缓慢。

You might succeed at optimising the query using a limit clause.您可能会成功地使用限制子句优化查询。 Adding a limit clause to query in QueryDSL is quite trivial: .limit(1) .在 QueryDSL 中为查询添加限制子句非常简单: .limit(1) So then your query becomes:那么你的查询就变成了:

JPQLQuery jpqlQuery = new JPAQuery(entityManager);
        jpqlQuery.select(qT1).from(qT1, qT2, qT3, qT4, qT5).where(booleanBuilder);
        jpqlQuery.limit(1);
        return jpqlQuery.fetch();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM