Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDsl - case expression with string value

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)

like image 630
wiecia Avatar asked May 27 '14 11:05

wiecia


1 Answers

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.

like image 100
Timo Westkämper Avatar answered Oct 21 '22 04:10

Timo Westkämper