Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java MongoDB一对多和多对一关系_Java_Mongodb_Spring Boot_Spring Data_Spring Data Mongodb - Fatal编程技术网

Java MongoDB一对多和多对一关系

Java MongoDB一对多和多对一关系,java,mongodb,spring-boot,spring-data,spring-data-mongodb,Java,Mongodb,Spring Boot,Spring Data,Spring Data Mongodb,我正在尝试优化我的MongoDB集合。例如: @Document class Article { @Id private String id; @DBRef(lazy = true) @CascadeSave private List<Comment> comments; private String title; private String text; // constructors, getters and se

我正在尝试优化我的MongoDB集合。例如:

@Document
class Article {
    @Id
    private String id;
    @DBRef(lazy = true)
    @CascadeSave
    private List<Comment> comments;
    private String title;
    private String text;

    // constructors, getters and setters are ommited
}

@Document
class Comment {

    @Id
    private String id;
    private String text;
    private String author;

    // constructors, getters and setters are ommited
}
@文档
班级文章{
@身份证
私有字符串id;
@DBRef(lazy=true)
@级联保存
私人名单评论;
私有字符串标题;
私有字符串文本;
//构造函数、getter和setter是常用的
}
@文件
课堂评论{
@身份证
私有字符串id;
私有字符串文本;
私有字符串作者;
//构造函数、getter和setter是常用的
}
看起来很简单。获取文章,然后获取本文的所有评论。但是如果我已经有了文章id,并且只想获得我文章的所有评论,那该怎么办呢?当然也很简单。每一条评论都应该引用它所属的文章(例如article_id)

我的问题是,我怎样才能自动做到这一点?如何在保存/更新等时将文章id插入评论?或者我应该向Comment类添加字段,然后首先保存文章,然后获取文章id,然后获取评论,添加文章id,保存评论并将评论添加到文章评论集合?这对我来说毫无意义

我使用的是Java10,SpringBoot2.0.5包括SpringDataMongoDB和反应式驱动程序。我还实现了@CascadeSave注释,用于在保存文章的同时保存注释


感谢您的回复。

您设计的模式是基于关系的设计。在Mongo中,您应该尽可能避免引用,因为在您的用例中,您可以将注释列表嵌入到文章中。
要在文章中保存注释,您可以使用
$push
功能,该功能也可在
springdatamongo

中使用,您设计的模式是基于关系的设计。在Mongo中,您应该尽可能避免引用,因为在您的用例中,您可以将注释列表嵌入到文章中。
要在文章中保存注释,您可以使用
$push
功能,该功能也可以在
spring-data-mongo

中使用,我已经决定使用关系数据库。谢谢,你说得对,我已经决定使用关系数据库。谢谢,你说得对