升级到 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: Query failed with error code 139 and error message 'ReferenceError: test_param_value is not defined :
我在这里看到了一些推荐这种处理可选参数的方式的答案((spring-data-mongo - optional query parameters?)),但它不再有效,而且我似乎无法在发布更改日志中找到任何内容。
最佳答案
如果其他人有兴趣,我在检查了类似的 ticket 后设法找到了解决方法进入 Spring Data 项目。
我在查询中检查空参数的方式似乎不是一个好的做法。这是来自 Spring 开发人员的评论:“占位符不是为了组合键/值而设计的,而是为了绑定(bind)参数。除此之外,在引号字符串中使用占位符在转义方面总是有问题的。使用 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);
关于 Spring 数据 mongodb : Optional @Query parameter no longer works,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43258077/