【问题标题】:JPA: Entity X has a OneToMany relationship to itself. How?JPA:实体 X 与自身具有 OneToMany 关系。如何?
【发布时间】:2010-10-27 02:52:05
【问题描述】:

我有一个实体调用Comment

Comment
+ 身份证 (PK)
+ fromUserId
+ 目标ID
+ replyId : 这是 id

的外键

这个想法是comment 可以有很多回复,但reply 也是comment。为了区分这两者,commentreplyId 等于 -1,同时 replyreplyId 的值为非 -1。最终,我想要Comment 拥有这样的List

List<Comment> replyList;  //So each comment will store all their replies into this List

在 JPA 中,我完成了两个实体之间的 OneToMany 关系,我在 @OneToMany@ManyToOne 注释的帮助下创建了一个列表,但在这种情况下我不知道如何完成这个。请帮忙

编辑
我创建评论的方式 - 回复布局是将一个数据表放在另一个数据表中

<h:form id="table">
<p:dataTable value="#{bean.comments}" var="item">
    <!-- Original Comment -->
    <p:column>
        <h:outputText value="#{item.comment}" />
    </p:column>

    <!-- Reply -->
    <p:column>
        <p:dataTable value="#{item.replies}" rendered="#{item.replies.size() > 0}" var="item2">
             <!-- Print out replies in here -->
             <h:outputText value="#{item2.comment}" />
        </p:dataTable>

        <!-- Text box and commandButton so user can add new reply -->
        <h:inputTextarea value="#{...}" />
        <p:commandButton value="Post" actionListener="#{bean.addReply(item)}" />
        <!-- Assume that I got this working, that a new Comment with correct REPLYTO_ID set -->
    </p:column>
</p:dataTable>
</h:form>

这是我的问题。当我输入回复并单击Post 时,它会在我的数据库中正确创建一个项目条目,然后调用getReplies()。此时我假设replies.size() == 1,但是replies.size() 等于0。因此我什么也看不到。我必须刷新页面,才能看到它显示正确。我在这里看到了问题,因为我通过#{item.replies} 生成了第二个表的值,因此如果item 没有更新到最新,那么replies 没有更新到最新。不确定这是 JSF 还是 JPA 问题

【问题讨论】:

    标签: jpa jakarta-ee one-to-many


    【解决方案1】:

    您可以像这样映射自引用实体:

    @Entity
    public class Comment {
        @Id
        private Long id;
    
        @ManyToOne(optional=true, fetch=FetchType.LAZY)
        @JoinColumn(name="REPLYTO_ID")
        private Comment replyTo;
    
        @OneToMany(mappedBy="replyTo")
        private List<Comment> replies = new ArrayList<Comment>();
    
        //...
    
        // link management method
        public void addToComments(Comment comment) {
            this.comments.add(comment);
            comment.setParent(parent);
        }
    }
    

    Comment 没有replyTo

    PS:确保正确设置双向关联。

    【讨论】:

    • 在 JPQL 中,如果您只想查找根 Comment,您可以这样说:SELECT c from COMMENT c WHERE c.replyTo IS NULL。对吗?
    • @Harry 是的,这就是我所说的“没有回复”的意思,根评论没有任何回复,所以它是空的。
    • 谢谢你,我得到了那个部分的工作。但是,我遇到了与您刚刚回答的问题相关的另一个问题。我写了一些代码,请你看看我的帖子,编辑部分。如果您愿意,我可以将其作为单独的问题发布,但我只是不知道该标题的内容。
    • @Harry 确定一下,您是否正确设置了关联的双方?
    • 是的。我实际上弄清楚出了什么问题。就像我说的,since I generated the value of the second table by #{item.replies}, therefore if item is not update to date, then replies is not update to date. 所以在我发布回复的方法中,我更新了原始 cmets 的列表。这解决了它。谢谢你的帮助。 :D
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 2010-11-16
    • 1970-01-01
    • 2019-02-10
    • 2021-12-21
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    相关资源
    最近更新 更多