简体   繁体   English

持久列表关系spring数据mongodb

[英]Persisting list relationship spring data mongodb

What's wrong, I tried to add new comment to comments list, the comment is mapped as list on Post class. 怎么了,我试图在评论列表中添加新评论,该评论被映射为Post类中的列表。

Here's my code. 这是我的代码。

Post.java 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 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);
}

The test fail with this error 测试失败,并显示此错误

org.springframework.data.mapping.model.MappingException: Cannot create a reference to an object with a NULL id. org.springframework.data.mapping.model.MappingException:无法创建对具有NULL ID的对象的引用。

All help appreciated ! 所有帮助表示赞赏!

Referencing to spring-data-mongodb docs 引用spring-data-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. 如果更改了Person对象引用的Account对象,则必须单独保存Account对象。 Calling save on the Person object will not automatically save the Account objects in the property accounts. 在Person对象上调用save不会自动将Account对象保存在属性帐户中。

Adding 新增中

commentRepository.save(comment);

before persisting Post object reslove the problem 坚持发布对象重新解决问题之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM