带有 Java 外键的 MongoDb [英] MongoDb with Java foreign key
问题描述
我需要使用 Java 在我的 MongoDB 中保存两个集合.其中一个集合是部门,另一个集合是员工.如果一个部门可以有很多员工,我想保存一个集合,例如必须将员工唯一 ID 映射到我的部门员工列表中.
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.
示例:
{
"_id" : ObjectId("598da19250aa4ad2413d4bc0"),
"_class" : "com.department",
"departmentName" : "SAQ-A",
"departmentNumber" : "3_2",
"employee" : [
"id" : "1",
"id" : "2",
"id" : "3"
]
}
我可以知道使用 Java 在 MongoDB 中实现它的方法是什么吗?
Can I know what is the way I can achieve it in MongoDB using Java?
推荐答案
通过提供的文档和标签,我假设您正在使用 spring 数据来处理 mongodb.所以在这里你可能想使用 DBRefs 将员工绑定到部门.幸运的是 Spring Data 给出你@DBRef注解.
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.
员工类:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Employee {
@Id
private Integer id;
...
}
部门类:
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 文档:
MongoDB document:
{
"_id" : ObjectId("598dc04ac4fdd0e29867ccbb"),
"_class" : "foo.bar.Department",
"employees" : [
{
"$ref" : "employee",
"$id" : 1
},
{
"$ref" : "employee",
"$id" : 2
}
]
}
注意: Employee 实例必须已经存在于 MongoDB 中.DBRef 不会以级联方式保存员工.看看这篇关于级联.
Note: Employee instance must already exist in MongoDB. DBRef will not save Employees in cascade style. Look at this article about cascading.
这篇关于带有 Java 外键的 MongoDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!