QueryDSL selecting values with alias from Sub Query

2.2k views Asked by At

I have two entities as below

Parent {
String parentID;
String parentName;
...
}

-

Child{
String parentID;
String childID;
Integer height;
....
}

Its a one to many relationship between the parent and the child.

My intention is have the below SQL.

    SELECT p.parentID, p.parentName, c.childrenHeightRange
    FROM
    Parent p
    INNER JOIN
    (
    SELECT parentID, (CASE WHEN (min(height) = max(height)) THEN cast(min(height) as varchar) ELSE cast(min(height) as varchar) + ' - '  + cast(max(height) as varchar) END) as childrenHeightRange
FROM Child GROUP BY parentID) as c
    ON (p.parentID = c.parentID)

For above query, I used a CaseBuilder for childHeightRange as below

   JPASubQuery subQuery = new JPASubQuery().from(child).groupBy(child.parentID);

    Expression<String> heightCaseExpression = new CaseBuilder()
            .when(child.height.min().eq(child.height.max()))
            .then(child.height.min().stringValue())
            .otherwise(child.height.min().stringValue() +"-"+child.height.max().stringValue())
            .as("childrenHeightRange");

And then comes the big question..

I have

query.from(parent).innerjoin(subquery.list(child.parentID,heightCaseExpression )).on(parent.parentID.eq(child.parentID))
 .list(parent.parentID,parent.parentName, ............);

How do i reference childrenHeightRange from the subquery?

Please help.

Thanks

1

There are 1 answers

0
Timo Westkämper On

In Querydsl JPA you can use subqueries only in the where part, so you will need to restructure your query.