I'm working to implement a Native query in QueryDSL and I'm getting a weird scenario where a value in a Case statement doesn't get saved into my Projected Java object. The source_field_amount in the THEN always comes back as 0.
I have a query like:
SELECT
(
CASE WHEN (field_A = 'N' OR field_A IS NULL)
THEN source_field_amount
ELSE 0
END
) AS targetFieldA,
(
CASE WHEN (field_B = 'Y')
THEN source_field_amount
ELSE 0
END
) AS targetFieldB,
FROM table
WHERE <some_condition>
I wrote that up in QueryDSL like this (it does a lot more but I'm simplifying).
private final SQLQueryFactory queryFactory;
public DataResponse testMethod() {
return queryFactory.select(Projections.bean(DataResponse.class, Expressions.cases()
.when(fieldA.eq("N").or(fieldA.isNull()))
.then(table.sourceFieldAmount)
.otherwise(BigDecimal.ZERO)
.as("targetFieldA"),
Expressions.cases()
.when(fieldA.eq("Y"))
.then(table.sourceFieldAmount)
.otherwise(BigDecimal.ZERO)
.as("targetFieldB"),
table.sourceFieldAmount))
.distinct()
.from(table)
.fetchOne();
}
@Data
public DataResponse {
private BigDecimal targetFieldA;
private BigDecimal targetFieldB;
private BigDecimal sourceFieldAmount;
}
When I hit this endpoint, I get 0 for both targetFieldA and targetFieldB. SourceFieldAmount here is for debugging and I get 0.76.
{
"targetFieldA": 0,
"targetFieldB": 0,
"sourceFieldAmount": 0.76,
}
I know that it's not always hitting that else condition as I've changed BigDecimal.ZERO to BigDecimal.TEN and it still prints 0.
Any idea what the problem is? I do have some case/when/then statements working fine in my code. I believe this used to work when I was using JPAExpressions, but I had to switch to the QueryDSL SQLQuery because of using a subQuery which isn't supported in JPAQuery from what I found.
I know I can just return the sourceFieldAmount and set the variables myself, but this was working well and cleaner to compare a provided Native Query with my QueryDSL, and I'm also trying to understand why it doesn't work. And I'm concerned I need to review the rest of my code and make sure none of these are broken elsewhere.