You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决MongoDB中Comment的Bug关联引用存储为null的问题

问题描述

我定义了Java类Comment和Bug,通过@DocumentReference实现双向关联:一个Bug包含多个Comment,每个Comment关联所属的Bug。我通过CommentService的addComment方法创建新Comment并添加到Bug的comments字段,但设置Comment的bug字段关联对应Bug后,Postman查看该字段显示为null,请问如何正确存储Bug关联引用?

Comment类代码

public class Comment {

    @Id
    private ObjectId id;

    private String text;
    private LocalDateTime created;
    @DocumentReference
    private Bug bug;
}

Bug类代码

public class Bug {

    @Id
    private ObjectId id;

    // private String projectId;

    private String title;
    private String description;
    private String priority; 
    private String status; 
    private LocalDateTime created;
    private LocalDateTime updated;

    @DocumentReference
    private List<Comment> comments;
}

当前使用的addComment方法

public Comment addComment(Comment comment, ObjectId bugId) {

        Optional<Bug> optionalBug = bugRepository.findById(bugId);
        if (optionalBug.isEmpty()) {
            throw new ResourceNotFoundException("Bug not found with ID: " + bugId);
        }

        comment.setCreated(LocalDateTime.now());
        Comment newComment = commentRepository.insert(comment);

        // 存储Bug引用至bug字段
        Bug bug = optionalBug.get();
        newComment.setBug(bug);

        // 关联Comment至Bug
        mongoTemplate.update(Bug.class)
                .matching(Criteria.where("_id").is(bugId))
                .apply(new Update().push("comments", newComment))
                .first();

        // 保存Comment至数据库
        return newComment;

    }
解决方案

问题核心是你设置newComment.setBug(bug)后,没有将修改后的Comment对象持久化到数据库。当前代码先插入了Comment,设置关联后仅返回对象但未做保存操作,导致数据库中Comment的bug字段仍为null。

有两种修正方式:

方式一:先设置关联再插入Comment

直接在插入Comment前就绑定关联的Bug对象,这样插入时就能把引用同步存储到数据库:

public Comment addComment(Comment comment, ObjectId bugId) {
    Optional<Bug> optionalBug = bugRepository.findById(bugId);
    if (optionalBug.isEmpty()) {
        throw new ResourceNotFoundException("Bug not found with ID: " + bugId);
    }

    comment.setCreated(LocalDateTime.now());
    Bug bug = optionalBug.get();
    comment.setBug(bug); // 先绑定Bug关联
    Comment newComment = commentRepository.insert(comment); // 插入时直接写入关联

    // 更新Bug的comments列表
    mongoTemplate.update(Bug.class)
            .matching(Criteria.where("_id").is(bugId))
            .apply(new Update().push("comments", newComment))
            .first();

    return newComment;
}

方式二:先插入再更新关联(需手动保存)

如果必须先插入Comment,设置关联后一定要调用save方法持久化修改:

public Comment addComment(Comment comment, ObjectId bugId) {
    Optional<Bug> optionalBug = bugRepository.findById(bugId);
    if (optionalBug.isEmpty()) {
        throw new ResourceNotFoundException("Bug not found with ID: " + bugId);
    }

    comment.setCreated(LocalDateTime.now());
    Comment newComment = commentRepository.insert(comment);

    Bug bug = optionalBug.get();
    newComment.setBug(bug);
    newComment = commentRepository.save(newComment); // 保存关联修改

    // 更新Bug的comments列表
    mongoTemplate.update(Bug.class)
            .matching(Criteria.where("_id").is(bugId))
            .apply(new Update().push("comments", newComment))
            .first();

    return newComment;
}

另外注意:@DocumentReference默认是延迟加载,后续查询Bug时若要直接获取comments列表,可通过Repository的查询方法触发关联加载,或配置@DocumentReference(lazy = false)改为立即加载。

内容的提问来源于stack exchange,提问作者dieudonne96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:35:00