'QueryDsl BooleanBuilder: How to create a predicate that compares another field?

I have simple example: to find all items that are sold out.

Item has initialQuantity and soldQuantity integer fields. (for some reason I need initialQuantity stored)

I'm trying to do something like:

builder = new BooleanBuilder();
Predicate predicate = builder.and(item.initialQuantity.eq(item.soldQuantity)).getValue();
Iterable<Item> iterable = itemRepository.findAll(predicate);

but it does not return as expected. ".eq()" looks like it expects an integer and not Path<>



Solution 1:[1]

First declare it :

JPAQueryFactory query = new JPAQueryFactory(em);
BooleanBuilder booleanBuilder = new BooleanBuilder();
QCreditRequest creditRequest = QCreditRequest.creditRequest;

Then, you can include your business logique, for example :

booleanBuilder.and(creditRequest.creditRequestId.eq(dataRequest.getCreditRequestId()));

if (StringUtils.isNotBlank(dataRequest.getProductId())){
                 booleanBuilder.and(creditRequest.product.productId.eq(dataRequest.getProductId()));}

finally return the result, mapped to your DTO :

return new HashSet<>(
            query
                .select(
                    Projections.constructor(
                        APResponse.class,
                        creditRequest.creditRequestId,
                        creditRequest.creditRequestDate,
                        creditRequest.product.productId,
                        creditRequest.creditRequestComment))
                .from(creditRequest)
                .innerJoin(creditRequest.product, product)
                .innerJoin(creditRequest.status, creditRequestStatus)
                .where(booleanBuilder)
                .fetch());

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