【问题标题】:How to use SpEL expression on Spring Data Mongodb?如何在 Spring Data Mongodb 上使用 SpEL 表达式?
【发布时间】:2018-07-31 03:49:52
【问题描述】:

我无法弄清楚如何将 SpEL 表达式用于我现有的查询和文档以获取新引入的字段。

例子:

@Document(collection = "abc")
public class Abc {

 private boolean deleted;
 public boolean isDeleted() {
  return deleted;
 }

 public void setDeleted(boolean deleted) {
  this.deleted = deleted;
 }

}

我已经在使用 Spring Data Mongodb

@Repository
public interface AbcRepository extends MongoRepository < Abc, String > {

 Abc findAllByDeleted(boolean deleted);

}

注意:我有近 1000 多个关于 abc 集合的文档。

我想在我的集合中引入新字段,例如状态,我的查询将发生变化,它不会返回任何内容,因为新字段 不存在 旧数据,我该怎么做处理这种情况?我不想做数据补丁。所以我发现我们可以从 spring data SpEL 表达式中使用存在。

https://docs.spring.io/spring-data/mongodb/docs/2.1.0.M3/reference/html/#mongodb.repositories.queries.json-spel

这是我的更改:

@Document(collection = "abc")
public class Abc {
...
...

private boolean status;
 public boolean isStatus() {
  return status;
 }

 public void setStatus(boolean status) {
  this.status = status;
 }
}

我的查询更改为

//Tried this but throwing exception
@Query("{'status' : {$exists :false}}")
Abc findAllByDeletedAndStatus(boolean deleted, boolean status);

如何使用 SpEL 表达式检查状态字段是否存在并应用从调用者传递的参数?

【问题讨论】:

    标签: java spring mongodb spring-boot spring-data


    【解决方案1】:

    我不确定完全理解您的要求,但请参阅下面的一些帮助。

    假设Abc 具有deletedstatus 属性:

    @Query("{ $and :[" +
              "?#{ { 'deleted' : [0] } }," +
              "?#{ { 'status' : [0] } }" +
             "]}")
      Abc findAllByDeletedAndStatus(boolean deleted, boolean status);
    

    如果你的参数是可选的,你可以使用这种方式(这在可选过滤器的情况下非常有用):

      @Query("{ $and :[" +
              "?#{ [0] == null ? { $where : 'true'} : { 'deleted' : [0] } }," +
              "?#{ [1] == null ? { $where : 'true'} : { 'status' : [1] } }" +
           "]}")
      Abc findAllByDeletedAndStatus(boolean deleted, boolean status);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 2011-09-29
      • 2017-07-20
      • 1970-01-01
      • 2016-06-27
      相关资源
      最近更新 更多