Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDSL: convert list of BooleanExpression to Predicate

Tags:

java

querydsl

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)
like image 943
Paweł Kozikowski Avatar asked Sep 01 '15 08:09

Paweł Kozikowski


1 Answers

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.

like image 172
JorgeC Avatar answered Oct 05 '22 08:10

JorgeC