Spring数据mongodb:可选的@Query参数不再有效

时间:2017-04-06 14:26:55

标签: 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)

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

  

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

我在这里看到了一些答案,建议这种处理可选参数的方式((spring-data-mongo - optional query parameters?))但它不再起作用,我似乎无法在发布更改日志中找到任何内容。

1 个答案:

答案 0 :(得分:3)

In case anyone else is interested, I managed to find a workaround after checking a similar ticket int the Spring Data project.

It seems the way I was checking for null parameters in the query is not a good practice. This is from a Spring developer comment: "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"

So I ended up using SpEL to do the checks on parameters and it works fine. This is how it looks:

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