QueryDSL: convert list of BooleanExpression to Predicate

11,538

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.

Share:
11,538
Paweł Kozikowski
Author by

Paweł Kozikowski

Updated on June 09, 2022

Comments

  • Paweł Kozikowski
    Paweł Kozikowski almost 2 years

    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)