'Querydsl: Putting enum constant in a query result

I encountered a use case in which I need to put enum constant in a query result. My query looks like this:

QTable qTable = QTable.table;

JPAQuery query = ...

SomeDTO someDTO = query.singleResult(Projections.fields(SomeDTO.class,
                ...,
                someBooleanExpression ? qTable.enumField : <ENUM_CONSTANT>,
                ...));

I am looking for a way to put some constant enum value in the place of ENUM_CONSTANT.

I tried Expresssions.as, Expressions.constantAs or EnumTemplate in various combinations, but none of them worked. I think there must be a simple way to fix this, but I just don't know how.

I'm looking for something like:

(MyEnum.MyValue).as("enumField")


Solution 1:[1]

Maybe you could try the CaseBuilder

Expression<MyEnum> cases = new CaseBuilder()
    .when(someBooleanExpression).then(qTable.enumField)
    .otherwise(MyEnum.ENUM_CONSTANT);

see reference

Solution 2:[2]

You can use this: com.querydsl.core.types.dsl.Expressions.constant(T value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krstf
Solution 2 Pedro Borges