QueryDSL:将BooleanExpression的列表转换为谓词

时间:2015-09-01 08:27:43

标签: java querydsl

我尝试创建一个取决于布尔参数数量的查询。创建谓词的函数如下所示:

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

问题是convertExpressionsToPredicate功能。 querydsl中是否有任何特殊方法可以使用or运算符将表达式列表连接到一个谓词中?

我正在寻找的解决方案应该转换为:

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

成:

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

2 个答案:

答案 0 :(得分:8)

要构造复杂的布尔表达式,请使用com.querydsl.core.BooleanBuilder类。它实现Predicate并且可以以级联形式使用。例如:

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是可变的,最初表示null。在每次andor调用后,它代表操作的结果。

答案 1 :(得分:0)

如果有人正在使用 Spring Boot JPA 和 QueryDSL,您可以使用以下命令获得 Page<YourType> 结果(在 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)
}