spring-data-mongo – 可选的查询参数?

我使用spring-data mongo和基于JSON的查询方法,并且不确定如何在搜索查询中允许可选参数。

例如 – 说我有以下function

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

– 但我不想应用名称正则表达式匹配,或者如果将NULL值传递给方法,则不应用日期范围限制。

目前,我可能不得不使用mongoTemplate构建查询。

有没有其他选择 – 或者使用mongoTemplate是最好的选择吗?

谢谢

要在布尔逻辑中实现此function,我将执行以下操作并转换为编程语言中可用的操作

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

在纯SQL中,这是完成的

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

在MongoDB中,这是通过$ where完成的

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

我们可以通过使用Mongo Operations来加速这一点 ,而不是以牺牲一些可读性为代价来构建函数。 不幸的是不起作用。

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

所以你拥有的是

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

这可以进一步扩展以处理in / all子句的数组

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

您可能有兴趣就此问题提供反馈或投票: https : //jira.springsource.org/browse/DATAJPA-209

它解决了这个问题。除了SD JPA。 似乎它适用于许多其他SD子项目。

给定的票据处理发现者通过“名称魔术”生成他们的SQL,例如findByTitleAndSubtitle(),现在可以正常工作。 但是当你用@Query注释这个查找器时仍然存在同样的问题(“select product where title =:title and subtitle =:subtitle”); null值被翻译成“subtitle = null”,因此将无法找到。