2012-07-23 65 views
14

我正在使用基於JSON的查詢方法的spring-data mongo,並且不確定如何在搜索查詢中允許可選參數。spring-data-mongo - 可選的查詢參數?

舉例來說 - 說我有以下功能

@Query("{ 'name' : {$regex : ?0, $options : 'i'}, 'createdDate' : {$gte : ?1, $lt : ?2 }} }") 
List<MyItem> getItemsLikeNameByDateRange(String name, Date startDateRange, Date endDateRange); 

- 但我沒有想申請的名稱正則表達式匹配,但是如果NULL值傳遞給方法不適用的日期範圍限制。

目前,它看起來像我可能要建立一個使用mongoTemplate查詢。

是否有任何的替代品 - 或正在使用mongoTemplate最好的選擇?

感謝

+0

現在我已經走下了使用Criteria類的路線。它看起來比在註釋中嵌入JSON查詢要乾淨得多,而且更容易定製檢索哪些字段。 – 2012-07-24 09:03:19

回答

16

要在布爾邏輯實現這一點,我做以下,並轉換爲在編程語言

:query != null -> field == :query 
!(:query != null) || (field == :query) 
(:query == null) || (field == :query) 

在普通的SQL都可以操作,這是因爲

where (null = :query) or (field = :query) 
完成

在MongoDB中,這是通過在$完成,其中

{ $where: '?0 == null || this.field == ?0' } 

我們可以通過使用Mongo的操作,而不是在一些可讀性爲代價建立的一切功能加快這有點。不幸的是無法工作。

{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] } 

所以,你有什麼

@Query("{ $or : [ { $where: '?0 == null' } , { field : ?0 } ] }") 
List<Something> findAll(String query, Pageable pageable); 

這可以進一步擴展到處理數組中/所有條款

@Query("{ $or : [ { $where: '?0.length == 0' } , { field : { $in : ?0 } } ] }") 
List<Something> findAll(String query, Pageable pageable); 
1

你可能有興趣在此提供反饋或投票問題: https://jira.springsource.org/browse/DATAJPA-209

它與涉及EXA這個問題,除了SD JPA。似乎它適用於許多其他SD子項目。

+0

謝謝,對此投了! – 2013-05-13 10:37:15

0

給定票證處理髮現者通過「名字魔法」生成他們的SQL,例如, findByTitleAndSubtitle(),現在工作正常。但是當你使用@Query(「select product where title =:title and subtitle =:subtitle」)註釋這個發現者時,仍然存在同樣的問題;空值被翻譯成「subtitle = null」,因此將不會被發現。