持久列表关系 spring 数据 mongodb

Persisting list relationship spring data mongodb

怎么了,我试图将新评论添加到评论列表,评论被映射为 Post class 上的列表。

这是我的代码。

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....
}

Comment.java

@Document
public class Comment {

    @Id
    private String id;
    private String comment;
    private int rating;

    // getters and setters....
}

Test.class

@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: Cannot create a reference to an object with a NULL id.

感谢所有帮助!

参考 spring-数据-mongodb 文档

Important The mapping framework does not handle cascading saves. If you change an Account object that is referenced by a Person object, you must save the Account object separately. Calling save on the Person object will not automatically save the Account objects in the property accounts.

添加

commentRepository.save(comment);

在坚持之前 Post object reslove the problem