Returning a QueryDSL BooleanExpression that evaluates to true

How do I return a BooleanExpression that evaluates to true?

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

I create a QueryDSLHelper class which has static methods which do the null check before adding the expression. Something like this:

public static void goe(BooleanBuilder builder, DateTimePath<Date> path, Date value) {
    if(date!=null) {
        builder.and(path.goe(value));
    }
}

public static void like(BooleanBuilder builder, StringPath path, String value) {
    if(value!=null) {
        builder.and(path.like(value));
    }
}

Now I can just statically import those methods and call them on one line:

        like(builder, book.isbn, isbn);

This is extremely useful and very clean/readable when implementing 'filter' or 'filterByExample' queries.

Although, the answer above from Timo is probably better solution.


With java 8 and BooleanBuilder you can achieve elegant way like this:

Java 8 Optional & Lambda

public final class ProductQuery {
    public static BooleanExpression nameEqualTo(String name){
        return ofNullable(name).map(QProduct.product.name::eq).orElse(null);
    }
}

BooleanBuilder

BooleanBuilder where = new BooleanBuilder()
    .and(ProductQuery.nameEqualTo(name));

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