【问题标题】:Spring data mongodb: Optional @Query parameter no longer worksSpring data mongodb:可选的@Query 参数不再起作用
【发布时间】:2017-04-06 14:26:55
【问题描述】:

升级到 spring data mongodb 1.10.1 后,运行以下查询时出现错误:

@Query("{$and :["
            + "{ $or : [ { $where: '?0 == null' } , { 'field1' : ?0 } ] },"
            + "{ $or : [ { $where: '?1 == null' } , { 'field2' : ?1 } ] },"
            + "]}")
public Page<Entity> findAll(String param1, String param2)

检查错误我看到 where 子句中的参数没有被引用,结果我得到:

org.springframework.data.mongodb.UncategorizedMongoDbException: 查询 失败,错误代码 139 和错误消息“ReferenceError: test_param_value 未定义:

我在这里看到一些答案推荐这种处理可选参数的方式 ((spring-data-mongo - optional query parameters?)),但它不再有效,而且我似乎在发布更改日志中找不到任何内容。

【问题讨论】:

  • 它不知道 ?0 或 ?1 是什么类型,它无法比较 undefined == null 因为它无法弄清楚什么是 undefined。希望这是有道理的。

标签: spring mongodb spring-data-mongodb


【解决方案1】:

如果其他人有兴趣,我在 Spring Data 项目中检查了类似的ticket int 后设法找到了解决方法。

我在查询中检查空参数的方式似乎不是一个好习惯。这是来自 Spring 开发人员的评论:“占位符的设计目的不是组合键/值,而是绑定参数。除此之外,在带引号的字符串中使用占位符在转义方面总是存在问题。使用 SpEL 应该适合您的需求”

所以我最终使用 SpEL 来检查参数,它工作正常。看起来是这样的:

@Query("{$and :[" 
        + "?#{ [0] == null ? { $where : 'true'} : { 'field1' : [0] } },"
        + "?#{ [1] == null ? { $where : 'true'} : { 'field2' : [1] } },"
        + "]}")
public Page<Entity> findAll(String param1, String param2, Pageable pageable);

【讨论】:

  • $where 的使用不会影响性能吗?因为它会对每个文档执行jsdocs.mongodb.com/v3.2/reference/operator/query/where/…
  • Pageable 对我不起作用,我的意思是它返回 '$where is not allowed in this context'
  • 在我的情况下,String.Empty 的参数因此无效验证不起作用。使用这个验证 [0].length == 0 对我有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2018-03-20
  • 2020-12-10
  • 2018-01-24
  • 2017-06-23
相关资源
最近更新 更多