I am trying to make Coalesce using QueryDSL with no luck.
Here is what I want to do: I have several Order objects that have OrderItem objects. Each OrderItem has a price (BigDecimal). For each Order I want to have an Order identifier, as well as the sum of its OrderItem values ββreturned in the tuple. My model and my query are actually a bit more complicated, and for this reason I have to make the amount in the subquery.
Here is what I wrote:
NumberSubQuery<BigDecimal> sumQuery = new HibernateSubQuery() .from(qOrderItem) .where(qOrderItem.order.eq(qOrder)) .unique(qOrderItem.price.sum()); HibernateQuery query = new HibernateQuery(session).from(qOrder) .list(new QOrderTuple(qOrder.id, sumQuery))
OrderTuple is a tuple that contains only two fields: id (long) and priceSum (BigDecimal).
The request I requested works correctly. Now I would like to make sure that if Order does not have an OrderItem , then sumQuery returns 0 (and not null , as it currently is). So I changed my subquery as follows:
NumberSubQuery<BigDecimal> sumQuery = new HibernateSubQuery() .from(qOrderItem) .where(qOrderItem.order.eq(qOrder)) .unique(qOrderItem.price.sum().coalesce(BigDecimal.ZERO));
The problem is that this code does not compile, since the type returned by unique() is now SimpleSubQuery<BigDecimal> . However, the QOrderTuple constructor requires NumberExpression<? extends BigDecimal> NumberExpression<? extends BigDecimal> , not a SimpleSubQuery<BigDecimal> .
I also tried adding asNumber() to coalesce() , but I got NumberExpression<?> , Which is also not accepted by the constructor. In the end, I tried explicit Java casts to compile the code, but it does not work at runtime:
java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysema.query.types.ConstructorExpression.newInstance(ConstructorExpression.java:131) at com.mysema.query.jpa.FactoryExpressionTransformer.transformTuple(FactoryExpressionTransformer.java:50) at org.hibernate.hql.HolderInstantiator.instantiate(HolderInstantiator.java:96) at org.hibernate.impl.ScrollableResultsImpl.prepareCurrentRow(ScrollableResultsImpl.java:268) at org.hibernate.impl.ScrollableResultsImpl.next(ScrollableResultsImpl.java:123)
Is there something I am doing wrong with coalesce syntax?
Thanks in advance