Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.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 spring数据mongodb持久化列表关系_Java_Spring_Mongodb_Spring Data_Spring Data Mongodb - Fatal编程技术网

Java spring数据mongodb持久化列表关系

Java spring数据mongodb持久化列表关系,java,spring,mongodb,spring-data,spring-data-mongodb,Java,Spring,Mongodb,Spring Data,Spring Data Mongodb,出了什么问题,我试图在评论列表中添加新的评论,该评论被映射为Post类上的列表 这是我的密码 Post.java @Document public class Post { @Id private String id; @DBRef private List<Comment> comments; public void addComment(Comment comment) { if (comments == null) {

出了什么问题,我试图在评论列表中添加新的评论,该评论被映射为Post类上的列表

这是我的密码

Post.java

@Document
public class Post {

    @Id
    private String id;

    @DBRef
    private List<Comment> comments;

    public void addComment(Comment comment) {
    if (comments == null) {
        comments = new ArrayList<>();
    }
    this.comments.add(comment);
    }
    // getters and setters....
}
测试类

@Test
public void savePostWithComments() {
    Post post = postRepository.findAll().get(1);

    Comment comment = new Comment();
    comment.setComment("comment");
    comment.setRating(5);

    post.addComment(comment);
    postRepository.save(post);
}
测试因此错误而失败

org.springframework.data.mapping.model.MappingException:无法创建对具有空id的对象的引用


感谢大家的帮助

引用spring数据mongodb文档

重要的 映射框架不处理级联保存。如果更改由Person对象引用的Account对象,则必须单独保存Account对象。对Person对象调用save不会自动将Account对象保存到property accounts中

添加

commentRepository.save(comment);

在持久化Post对象之前,请解决引用spring数据mongodb文档的问题

重要的 映射框架不处理级联保存。如果更改由Person对象引用的Account对象,则必须单独保存Account对象。对Person对象调用save不会自动将Account对象保存到property accounts中

添加

commentRepository.save(comment);
在坚持Post对象之前,我喜欢这个问题