How can I dynamically add where clauses with querydsl?

soilworker picture soilworker · Dec 9, 2014 · Viewed 7.3k times · Source

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

Answer

Timo Westkämper picture Timo Westkämper · Dec 9, 2014

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