【问题标题】:Spring boot mongo - How to refer to document in other collections from a collectionSpring boot mongo - 如何从集合中引用其他集合中的文档
【发布时间】:2018-05-27 23:41:11
【问题描述】:

我有 Office 对象:

class Office{
   String address;
   int employees;
   String city;
   String State;
   ---- lot of other fields
}

我有mongo Office 类的集合,可以说上面的 Office 类代表 100 个 Office 文档。

然后我有 Employee 类:

class Employee{
   String firstName;
   String lastName;
   Office office;
   -----other fields
}

在 Employee 类的 mongo 集合中,我如何防止为每个 Employee 条目复制 Office 对象。

spring-boot mongodb 中,我是否可以引用 Office 集合来表示 Employee 的 Office 对象,而不是为 mongo db 中的每个员工复制它。我希望我已经解释了我的问题。

提前致谢。

【问题讨论】:

    标签: mongodb spring-boot


    【解决方案1】:

    您可以在 Mongo 中使用 DBRef。 Spring Data 带来了一个注解:

    @DBRef

    但是,请注意,MongoDB 是一种面向文档的 NoSQL,并且是在文档中嵌入内容的好习惯。这种方法可能会给您带来更大的问题。

    编辑:

    像这样使用@DBRefhttps://docs.spring.io/spring-data/data-mongo/docs/1.7.0.RELEASE/reference/html/#mapping-usage-references

    【讨论】:

      【解决方案2】:

      这是您可以使用的代码:

      @Document(collection="person")
      public class Person
      {
      
              @Id
              private Long personId;
      
              private String name;
      
              private int age;
      
              @DBRef(db="address")
              private List<Address> addresses = new ArrayList<Address>();
      
      //other getters and setters
      
      }
      

      【讨论】:

        【解决方案3】:

        以您的示例为基础:

        @Document
        class Employee {
           private String firstName;
           private String lastName;
        
           @DBRef
           private Office office;
        
           /* other fields */
        }
        

        【讨论】:

          猜你喜欢
          • 2021-09-23
          • 1970-01-01
          • 1970-01-01
          • 2021-04-19
          • 2021-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-30
          相关资源
          最近更新 更多