如何使用querydsl动态添加where子句?

时间:2014-12-09 12:56:00

标签: java querydsl

我一直在寻找文档的一些时间,并尝试了几件事,但我无法动态添加querydsl的where子句:

伪代码,我需要类似" if":

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

或者更好的是whereIf:

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

我到目前为止唯一发现的是使用BooleanBuilder,但我认为有更好的方法(如上面的伪代码)。

亲切的问候, soilworker

1 个答案:

答案 0 :(得分:10)

应该像这样工作

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

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