Search code examples
javaquerydsl

How can I dynamically add where clauses with querydsl?


I've been looking for some time now on the documentation and tried several things but I was not able to dynamically add where clauses with querydsl:

Pseudocode, I need something like the "if":

boolean addWhereClause = false; 
QAddress address = QAddress.address; 
JPQLQuery query = new JPAQuery(getEntityManager()); 
query.from(address)
     .if(addWhereClause).where(address.company.isNotNull())

or maybe better a whereIf:

boolean addWhereClause = false; 
QAddress address = QAddress.address; 
JPQLQuery query = new JPAQuery(getEntityManager()); 
query.from(address)
     .whereIf(addWhereClause, address.company.isNotNull())

The only thing I've found so far is using a BooleanBuilder, but I think there is a better way(like the pseudocode above).

kind regards, soilworker


Solution

  • It should work like this

    boolean addWhereClause; 
    QAddress address = QAddress.address; 
    JPQLQuery query = new JPAQuery(getEntityManager()); 
    query.from(address);    
    if (addWhereClause) {
        query.where(address.company.isNotNull());
    }
    

    or

    boolean addWhereClause; 
    QAddress address = QAddress.address; 
    JPQLQuery query = new JPAQuery(getEntityManager()); 
    query.from(address)
         .where(addWhereClause ? address.company.isNotNull() : null);