简体   繁体   中英

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)

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.

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)
}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM