Search code examples
javaspring-bootquerydsl

Querydsl - How to get sum of columns


These below is my STOCK TABLE info

id, bigint(20)
available_quantity, int(11)
allocation_quantity, int(11)
stop_quantity, int(11)
damage_quantity, int(11)
standby_quantity, int(11)

I'd like to do a query than in sql it's:

SELECT 
 available_quantity,
 allocation_quantity,
 stop_quantity,
 damage_quantity,
 standby_quantity,
 available_quantity + allocation_quantity + standby_quantity
FROM STOCK

I tried searching for the solution, but the closest I get was:

     return queryFactory
                .select(new QStockResponseDto(
                        stock.availableQuantity,
                        stock.standbyQuantity,
                        stock.allocationQuantity,
                        stock.availableQuantity + stock.standbyQuantity + stock.allocationQuantity 
                )).from(stock)

but this indicates below error

Operator '+' cannot be applied to 'com.querydsl.core.types.dsl.NumberPath<java.lang.Integer>', 'com.querydsl.core.types.dsl.NumberPath<java.lang.Integer>'

i don't know how to get this 'available_quantity + allocation_quantity + standby_quantity' in QueryDSL:


Solution

  • The error message gives you a great hint about the issue. The value stock.availableQuantity, stock.standbyQuantity, and stock.allocationQuantity are all objects of type NumberExpression. Read the NumberExpression documentation here:

    https://querydsl.com/static/querydsl/latest/apidocs/com/querydsl/core/types/dsl/NumberExpression.html

    I do not have QueryDSL set up local at this time to validate this, but I think you simply need to replace:

    stock.availableQuantity + stock.standbyQuantity + stock.allocationQuantity
    

    with this:

    stock.availableQuantity.add(stock.standbyQuantity).add(stock.allocationQuantity)
    

    If you need to provide an alias for that result, append the .as(Path<>) method after the second add() method. Let us know if this works.