具有元组条件的QueryDSL和SubQuery

Gui*_* F. 6 java syntax hibernate jpa querydsl

我试图在QueryDSL中编写一个查询来获取由其parentId分组的表中最旧的元素.

SQL等价物应该是:

SELECT a.* FROM child a
    INNER JOIN
    (
        SELECT parentId, MAX(revision) FROM child GROUP BY parentId
    ) b
    ON ( 
        a.parentId = b.parentId AND a.revision = b.revision
    )
Run Code Online (Sandbox Code Playgroud)

现在在QueryDSL中,我坚持使用语法.

JPQLQuery<Tuple> subquery = JPAExpressions
                .select(child.parent, child.revision.max())
                .from(child)
                .groupBy(child.parent);

HibernateQuery<Child> query = new HibernateQuery<>(session);
query.from(child)
    .where(child.parent.eq(subquery.???).and(child.revision.eq(subquery.???))));
Run Code Online (Sandbox Code Playgroud)

如何使用子查询编写此查询?

表格看起来像这样:

___parent___ (not used in this query, but exists)
parentId
P1       | *
P2       | *
P3       | *

___child___
parentId | revision
P1       | 1       | *
P1       | 2       | *
P1       | 3       | *
P2       | 2       | *
P2       | 3       | *
P3       | 1       | *

___result from child, the highest revision for each parentId___
P1       | 3       | *
P2       | 3       | *
P3       | 1       | *

到目前为止我尝试过的:

.where(JPAExpressions.select(child.parent,child.revision).eq(subquery));

-> org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree
Run Code Online (Sandbox Code Playgroud)

和许多语法错误......

我现在使用脏循环,因为我还没有找到解决方案.

Tim*_*imi 6

您可以使用Expressions.list()为 in 子句指定多列:

query.from(child).where(Expressions.list(child.parent, child.revision).in(subquery));
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用innerJoin(),就像在原始 SQL 中一样。