jsc*_*jsc 3 spring mongodb spring-data-mongodb
升级到 spring 数据 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)
Run Code Online (Sandbox Code Playgroud)
检查错误我看到 where 子句中的参数没有被引用,结果我得到:
org.springframework.data.mongodb.UncategorizedMongoDbException:查询失败,错误代码为 139,错误消息为“ReferenceError: test_param_value 未定义”:
我在这里看到一些答案,推荐这种处理可选参数的方式((spring-data-mongo - 可选查询参数?)),但它不再有效,我似乎无法在发布更改日志中找到任何内容。
如果其他人有兴趣,我在 Spring Data 项目中检查了类似的票证后设法找到了解决方法。
我在查询中检查空参数的方式似乎不是一个好习惯。这是来自 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2643 次 |
| 最近记录: |