2014-03-14 86 views
0

我有一個搜索表單用於搜索我的web應用程序中的房屋。表格具有以下字段,用查詢生成器在MongoDB中進行動態查詢

private String type; 
private Long minPrice; 
private Long maxPrice; 
private Integer minBedRooms; 

此表格用於在所有字段中輸入數據時使用搜索房屋。例如,用戶分別在所有字段中輸入數據"Rent 200 5000 2"。我對這個查詢

Query query = new Query(where("type") 
      .is(form.getType()) 
      .and("bedrooms") 
      .is(form.getMinBedRooms()) 
      .andOperator(where("price").lte(form.getMaxPrice()), 
        where("price").gte(form.getMinPrice()))); 

現在,當我離開上述領域的一個空白,它返回0結果。例如,當maxPrice爲空時,它將返回0結果。我的問題是我應該如何編寫上面的查詢,以便它可以填充null值。例如,我離開maxPriceminBedRooms領域清空它將搜索基礎上,typeminPrice

我使用的彈簧4和彈簧數據與MongoDB的

我一直堅持這一兩天數據,我將非常感謝任何形式的幫助。 問候,

回答

2

的下面是等效的,但它周圍添加邏輯測試

Query query = new Query(); 

    if (form.getType() != null) { 
     query.addCriteria(Criteria.where("type") 
     .is(form.getType()); 
    } 

    if (form.getMinBedrooms() != 0) { 
     query.addCriteira(Criteria.where("bedrooms") 
     .is(form.getMinBedRooms()) 
    } 

等。所以只需使用Query對象並添加條件即可。

+0

非常感謝你 – Shahzeb