2015-10-23 73 views
0

我需要幫助創建一個謂詞以用於Spring數據和querydsl。我正在將道斯轉換爲存儲庫。我遇到了一個有動態查詢的文章。我可以從列表創建一個謂詞,但是我迷失在如何從地圖創建動態謂詞。下面是從DaoImpl我是從轉換代碼:從地圖創建querydsl謂詞

public Set<String> getDocumentsByDocumentAssociation(Map.Entry<String,String>[] associations) { 
String queryStr = "SELECT da FROM DocumentExternalAssocEntity as da WHERE"; 
     StringBuilder sb = new StringBuilder(queryStr); 

    //loop through inputs. for first loop, skip appending the OR statements. Append OR for all others 
    for (int i = 0; i < associations.length; i++){ 
     if (i > 0) { 
      sb.append(" OR"); 
     } 
     String whereString = " (da.associationtype = :docAssocType" + i + " AND da.associationvalue = :docAssocValue" + i + ")"; 
     sb.append(whereString); 
    } 

    //query when previous loop is done appending 
    final Query query = em.createQuery(sb.toString());   
    for(int i = 0; i < associations.length; i++) { 
     query.setParameter("docAssocType" + i, associations[i].getKey()); 
     query.setParameter("docAssocValue" + i, associations[i].getValue()); 
    } 

,這裏是相關的生成類:

private static final long serialVersionUID = 1971644089L; 

public static final QDocumentExternalAssocEntity documentExternalAssocEntity = new QDocumentExternalAssocEntity("documentExternalAssocEntity"); 

public final StringPath associationtype = createString("associationtype"); 

public final StringPath associationvalue = createString("associationvalue"); 

感謝,讓我知道如果你需要任何額外的信息

回答

0

這應做到:

BooleanExpression expr = null; 
for (int i = 0; i < associations.length; i++){ 
    BooleanExpression innerExpr = 
     documentExternalAssocEntity.associationtype.eq(associations[i].getKey()) 
      .and(documentExternalAssocEntity.associationvalue.eq(associations[i].getValue())) 
    if (expr == null) { 
     expr = innerExpr; 
    } else { 
     expr = expr.or(innerExpr); 
    } 
} 
+0

爲聚集你也可以使用'BooleanBuilder'。 –