Hibernate cast from double to BigDecimal

We are using criteriaBuilder to fetch data from DB.
We used to have smth like
criteriaBuilder.avg(root.get(SOME_PARAM)).as(BigDecimal.class)

However after spring update fromn 3.1.1 β†’ 3.4.1 it seems that the cast to big decimal stopped working. It returns double and we are expecting BigDecimal in constructor and very much prefer not to change it.
Tried to do fix it doing something like

Expression<Double> avgExpression = criteriaBuilder.avg(root.get(SOME_PARAM));
Expression<BigDecimal> castedAvg = criteriaBuilder.function("cast", BigDecimal.class, avgExpression);

Got exception that function cast() has 2 parameters, but 1 arguments given.

Or something like

Expression<Double> avgExpression = criteriaBuilder.avg(root.get(SOME_PARAM));
Expression<BigDecimal> castedAvg =  criteriaBuilder.function("cast", BigDecimal.class, avgExpression, criteriaBuilder.literal("as DECIMAL"));

Got exception that QueryLiteral cannot be cast to CastTarget.

How can we cast from double to BigDecimal using criteriaBuilder?

See CriteriaBuilder cast function example - #4 by isivanoff.

1 Like

Thank you for your swift reply!
Tried that as well like so:

JpaExpression<BigDecimal> castedAvg = ((JpaExpression<BigDecimal>) criteriaBuilder.avg(root.get(CUSTOM_PARAM))).cast(BigDecimal.class);

It gives

Inconvertible types; cannot cast β€˜jakarta. persistence. criteria. Expression<java. lang. Double>’ to β€˜org. hibernate. query. criteria. JpaExpression<java. math. BigDecimal>’

Sorry, my bad, should have been like this

JpaExpression<BigDecimal> castedAvg =
                ((JpaExpression<Double>) criteriaBuilder.avg(root.get(CUSTOM_PARAM))).cast(BigDecimal.class);

It works