QueryDsl - case expression with string value

wiecia picture wiecia · May 27, 2014 · Viewed 11.7k times · Source

QueryDsl 3.3.4
Hibernate 3.6.10-Final I have two entities:

public class Document {
    private Confirmation confirmation;
}

public class Confirmation {
    ...
}

I need a query like this:

SELECT count(d.id), CASE WHEN d.confirmation_id IS NULL then 'NOT_CONFIRMED' else 'CONFIRMED' END as confirmed FROM document d GROUP BY confirmed;

So it should be grouped by the result of case expression above.
Now, to translate the case part to querydsl:

StringExpression confirmExp = new CaseBuilder()
    .when(Expressions.booleanTemplate("confirmation_id is null"))
    .then(Expressions.stringTemplate("NOT_CONFIRMED"))
    .otherwise(Expressions.stringTemplate("CONFIRMED"));

I'm using .when(Expressions.booleanTemplate("confirmation_id is null")) to avoid joining on confirmation table. Running the query with such expression I'm getting an exception below.
Is this another hibernate bug or such case needs to be differently?

java.lang.IllegalStateException: No data type for node: >org.hibernate.hql.ast.tree.CaseNode +-[CASE] CaseNode: 'case' | +-[WHEN] SqlNode: 'when' | | +-[IS_NULL] IsNullLogicOperatorNode: 'is null' | | | -[IDENT] IdentNode: 'confirmation_id' {originalText=confirmation_id} | | -[IDENT] IdentNode: 'NOT_CONFIRMED' {originalText=NOT_CONFIRMED} | -[ELSE] SqlNode: 'else' | -[IDENT] IdentNode: 'CONFIRMED' {originalText=CONFIRMED}

org.hibernate.hql.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:156)

Answer

Timo Westkämper picture Timo Westkämper · May 27, 2014

If you want String literals in the query you need to write it as

StringExpression confirmExp = new CaseBuilder()
    .when(Expressions.booleanTemplate("confirmation_id is null"))
    .then(Expressions.stringTemplate("'NOT_CONFIRMED'"))
    .otherwise(Expressions.stringTemplate("'CONFIRMED'"));

Expressions.stringTemplate doesn't mean that the argument is serialized as a String literal, but that the created expression is of type java.lang.String.