【问题标题】:Persisting list relationship spring data mongodb持久化列表关系spring数据mongodb
【发布时间】:2023-03-16 02:50:01
【问题描述】:

怎么了,我尝试在 cmets 列表中添加新评论,评论被映射为 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....
}

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:无法创建对具有 NULL id 的对象的引用。

感谢所有帮助!

【问题讨论】:

    标签: java spring mongodb spring-data spring-data-mongodb


    【解决方案1】:

    参考 spring-data-mongodb 文档

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

    添加

    commentRepository.save(comment);
    

    在持久化 Post 对象之前解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 2015-07-27
      • 2020-06-15
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      相关资源
      最近更新 更多