MongoDb with Java foreign key

前端 未结 2 867
旧巷少年郎
旧巷少年郎 2021-01-24 22:44

I need to save two collections in my MongoDB using Java. Where one collection is Department and other collection is Employee. Where one Departm

相关标签:
2条回答
  • 2021-01-24 23:01

    If $id didn't work try just id like this

    "employees" : [ { "$ref" : "employee", "id" : 1 }, { "$ref" : "employee", "id" : 2 } ]

    0 讨论(0)
  • 2021-01-24 23:12

    By the provided document and tags I assume you are using spring data to deal with mongodb. So here you may want to use DBRefs to bind employees into departments. Luckily Spring Data gives you @DBRef annotation.

    Employee class:

    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document
    public class Employee {
    
        @Id
        private Integer id;
        ...
    
    }
    

    Department class:

    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.DBRef;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document
    public class Department {
    
        @Id
        private String id;
    
        @DBRef
        private Collection<Employee> employees;
        ...
    }
    

    MongoDB document:

    {
        "_id" : ObjectId("598dc04ac4fdd0e29867ccbb"),
        "_class" : "foo.bar.Department",
        "employees" : [ 
            {
                "$ref" : "employee",
                "$id" : 1
            }, 
            {
                "$ref" : "employee",
                "$id" : 2
            }
        ]
    }
    

    Note: Employee instance must already exist in MongoDB. DBRef will not save Employees in cascade style. Look at this article about cascading.

    0 讨论(0)
提交回复
热议问题