简体   繁体   中英

MongoDb with Java foreign key

I need to save two collections in my MongoDB using Java. Where one collection is Department and other collection is Employee . Where one Department can have many employees I want to save a collection like an employee unique ID has to mapped in my department employee list.

Example:

{
    "_id" : ObjectId("598da19250aa4ad2413d4bc0"),
    "_class" : "com.department",
    "departmentName" : "SAQ-A",
    "departmentNumber" : "3_2",
    "employee" : [ 
           "id" : "1",
           "id" : "2",
           "id" : "3"
     ]
}

Can I know what is the way I can achieve it in MongoDB using Java?

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM