Spring 数据 mongodb:可选的@Query 参数不再有效
Spring data mongodb: Optional @Query parameter no longer works
升级到 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?)),但它不再有效,而且我似乎无法在发布更改日志中找到任何内容。
如果其他人有兴趣,我在检查了 Spring 数据项目中的一个类似 ticket 后设法找到了解决方法。
我在查询中检查空参数的方式似乎不是一个好的做法。这来自 Spring 开发者评论:"placeholders are not designed to compose keys/values but bind parameters. Beyond that, placeholder use in quoted strings is always problematic in terms of escaping. Using SpEL should suit your needs"
所以我最终使用 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 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?)),但它不再有效,而且我似乎无法在发布更改日志中找到任何内容。
如果其他人有兴趣,我在检查了 Spring 数据项目中的一个类似 ticket 后设法找到了解决方法。
我在查询中检查空参数的方式似乎不是一个好的做法。这来自 Spring 开发者评论:"placeholders are not designed to compose keys/values but bind parameters. Beyond that, placeholder use in quoted strings is always problematic in terms of escaping. Using SpEL should suit your needs"
所以我最终使用 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);