Search code examples
javaquerydsl

Querydsl : build case statement with varying number of when/then pairs


Using querydsl, I came across a problem where I need to generate a case statement with varying number of when/then statements and an ultimate else expression.

As described here, I have been able to generate case statement with fixed number of when/then statements easily like this-

Expression<String> cases = customer.annualSpending
    .when(10000).then("Premier")
    .when(5000).then("Gold")
    .when(2000).then("Silver")
    .otherwise("Bronze");

This is the approach I have already tried with no success-

Map<BooleanBuilder,SimplePath<?>> caseExpressionMap = new LinkedHashMap<>();    
CaseBuilder.Cases<?,?> caseExpression = null;
for(BooleanBuilder expression : caseExpressionMap.keySet()){
  if(caseExpression!=null)
    caseExpression = caseExpression.when(expression).then(caseExpressionMap.get(expression));
 else
    caseExpression = new CaseBuilder().when(expression).then(caseExpressionMap.get(expression));
}
cases=cases.otherwise(...)

I ran into some type issue -

The method then(capture#19-of ?) in the type CaseBuilder.CaseWhen is not applicable for the arguments (SimplePath)

Appreciate some help here.


Solution

  • Changing the generics of CaseBuilder did the job. This code will work-

    Map<BooleanBuilder,String> caseExpressionMap = new LinkedHashMap<>();
    CaseBuilder.Cases<String,SimpleExpression<String>> cases = null;
    for(BooleanBuilder expression : caseExpressionMap.keySet()){
      if(caseExpression!=null)
        caseExpression = caseExpression.when(expression).then(caseExpressionMap.get(expression));
     else
        caseExpression = new CaseBuilder().when(expression).then(caseExpressionMap.get(expression));
    }
    cases=cases.otherwise(...)