Search code examples
javanullquerydsl

Returning a QueryDSL BooleanExpression that evaluates to true


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?

Solution

  • You can safely use null predicates like this

    private BooleanExpression isFirstNameLike(String firstName){
        return firstName != null ? customer.firstName.like(firstName) : null;        
    }
    
    private BooleanExpression isStatusEq(StatusEnum status){
        return status != null ? customer.status.eq(status) : null;
    }
    

    And use the varargs aspect of where

    query.from(customer)
         .where(
             isFirstNameLike(customerQueryInfo.getFirstName()),
             isLastNameLike(customerQueryInfo.getLastName()),
             isStatusEq(customerQueryInfo.getStatus()))
         .list(customer);