Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically add where clauses with querydsl?

Tags:

java

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

like image 725
soilworker Avatar asked Dec 09 '14 12:12

soilworker


1 Answers

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);
like image 70
Timo Westkämper Avatar answered Oct 31 '22 15:10

Timo Westkämper