Returning a QueryDSL BooleanExpression that evaluates to true

balteo picture balteo · Sep 5, 2012 · Viewed 28.2k times · Source

Say I have CustomerQueryInfo bean with the following properties:

  • String firstName
  • String lastName
  • StatusEnum status

I want to perform a "QueryDSL" search using this an object of this type that will return a list of customers List<Customer>.

If one of the fields of CustomerQueryInfo is null, I don't want to use it in the search. Thus a CustomerQueryInfo object with all three fields set to null will return all customers.

I am looking for best practices to perform such a search with QueryDSL.

Is something like this OK:

private BooleanExpression isFirstNameLike(String firstName){
    if(firstName==null)
        return true BooleanExpression somehow;
    return QCustomer.customer.firstName.like(firstName);
}

private BooleanExpression isStatutEq(StatusEnum status){
    if(status==null)
        return true BooleanExpression somehow;
    return QCustomer.customer.status.eq(status);
}

then:

return query.from(customer).where(isFirstNameLike(customerQueryInfo.getFirstName).and(isLastNameLike(customerQueryInfo.getLastName).and(isStatusEq(customerQueryInfo.getStatus))).list;
  1. How do I return a BooleanExpression that evaluates to true?
  2. If the above approach is not advisable, then what is the recommended best practice?

Answer

Fabian Barney picture Fabian Barney · Oct 9, 2017

How do I return a BooleanExpression that evaluates to true?

BooleanExpression alwaysTrue = Expressions.asBoolean(true).isTrue();