'QueryDSL: convert list of BooleanExpression to Predicate

I'm trying to create a query that would depend on number of boolean parameters. The function that creates the predicate looks like this:

Predicate createPredicate(Boolean param1, Boolean param2) {
    List<BooleanExpression> booleanExpressions = new List<>();        
    if (param1)
        booleanExpressions.add(/** expression 1 **/);
    if (param2)
        booleanExpressions.add(/** expression 2 **/);
    convertExpressionsToPredicate(booleanExpressions);
}

The problem is the convertExpressionsToPredicate function. Is there any special method in querydsl to join list of expressions into one predicate using the or operator?

The solution I'm looking for should convert this:

List<BooleanExpression> booleanExpressions = List(exp1, exp2, exp3);

into:

Predicate p = exp1.or(exp2).or(exp3)


Solution 1:[1]

To construct complex boolean expressions, use the com.querydsl.core.BooleanBuilder class. It implements Predicate and can be used in cascaded form. For example:

public List<Customer> getCustomer(String... names) {
    QCustomer customer = QCustomer.customer;
    JPAQuery<Customer> query = queryFactory.selectFrom(customer);
    BooleanBuilder builder = new BooleanBuilder();
    for (String name : names) {
        builder.or(customer.name.eq(name));
    }
    query.where(builder);
    return query.fetch();
}

BooleanBuilder is mutable and initially represents null. After each and or or call it represents the result of the operation.

Solution 2:[2]

If anybody is using Spring Boot JPA and QueryDSL, you can use the following to get a Page<YourType> result (in Kotlin):

fun listCards(page: Int?, pageSize: Int?, orderColumnName: String?, orderDirection: Sort.Direction?, filter: CardFilter?): Page<Card> {
  val pageRequest = PageRequest.of(page ?: 0, pageSize ?: 10, orderDirection ?: Sort.Direction.ASC, orderColumnName ?: Card::cardNumber.name)
  val conditions = BooleanBuilder()
  filter?.cardNumber?.let { qCard.cardNumber.contains(it) }?.let { conditions.and(it) }
  filter?.cardHolderName?.let { qCard.cardHolderName.containsIgnoreCase(it) }?.let { conditions.and(it) }
  filter?.phoneNumber?.let { qCard.phoneNumber.contains(it) }?.let { conditions.and(it) }
  filter?.email?.let { qCard.email.contains(it) }?.let { conditions.and(it) }
  filter?.locale?.let { qCard.locale.eq(it) }?.let { conditions.and(it) }

  if (conditions.hasValue()) {
    return cardRepository.findAll(conditions.value!!, pageRequest)
  }
  return cardRepository.findAll(pageRequest)
}

Solution 3:[3]

ExpressionUtils.allOf(ps) // use AND join conditions, ps is a list of predicate
ExpressionUtils.anyOf(ps) // use OR join conditions, ps is a list of predicate

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 David Newcomb
Solution 2 hamid
Solution 3 drrr