【问题标题】:Mapping a Collection without using DBRef (Spring Data MongoDB)不使用 DBRef 映射集合(Spring Data MongoDB)
【发布时间】:2015-10-31 09:42:28
【问题描述】:

我读过很多文章,不鼓励在 Spring Data/MongoDB 中使用 DBRef 进行集合映射。那么,如何实现一个映射来存储从 students 集合中的这些对象中获取的 ObjectId 数组?

假设我有以下 POJO 模型:

@Document (collection = "courses")
public class Course {

    @Id
    private String id;

    private String name;

    private List<Student> students = new LinkedList<Student>();

    //.. constructors, getters and setters ..
}

public interface CourseRepository extends MongoRepository<Course, String> { }

结果应该是这样的:

courses
{
    _id : ObjectId("foo"),
    _class: "model.Course",
    name: "MongoDB for Dummies",
    students: [ ObjectId("foo2"), ObjectId("foo3"), ... ]
}

而不是这个:

courses
{
    _id : ObjectId("foo"),
    _class: "model.Course",
    name: "MongoDB for Dummies",
    students: [ 
             DBRef("student", ObjectId("foo2")),
             DBRef("student", ObjectId("foo3"))
    ]
}

谢谢!

【问题讨论】:

    标签: mongodb mapping spring-data spring-data-mongodb


    【解决方案1】:

    您可能想尝试显而易见的方法并将students 更改为List&lt;ObjectId&gt;。 ;)

    【讨论】:

    • 没关系!这解决了拥有 ObjectId 数组的问题。但在那种情况下,我的 POJO 模型受到 db 模型的影响;我的 Course 对象将不再包含 Student 对象列表。也许我从错误的角度来看这个,但删除 List 不是一个缺点吗?
    • 我应该使用 List studentsIds 和 @Transient List 学生吗?请用知识扇我耳光!大声笑
    • 对此没有进一步的答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2017-10-31
    • 2021-04-03
    • 2021-04-20
    • 1970-01-01
    • 2012-02-28
    相关资源
    最近更新 更多