使用 JPA 和 Hibernate 构建与“两个父级”(实体和视图)的 OneToMany 关系

问题描述 投票:0回答:1

考虑到以下博客文章与其评论之间的经典

OneToMany
关系:

// parent entity
@Entity
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PostComment> comments = new ArrayList<>();
}

// child entity
@Entity
@Table(name = "post_comment")
public class PostComment {

    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "post_id", referencedColumnName = "post_id")
    private Post post;
}

现在,我们的数据库提供了一个连接其他几个表的附加视图。我们称之为

view_post
。帖子评论列表应该是此视图的一部分,如下所示:

@Entity
@Immutable
@Table(name = "view_post")
public class PostView {

    @Id
    private Long id;

    // other fields omitted...

    @OneToMany(mappedBy = "post")
    private List<PostComment> comments;
}

然而,这并不像异常所明确表明的那样工作:

Association 'ViewPost.comments' is 'mappedBy' a property named 'post' which references the wrong entity type 'Post', expected 'ViewPost'

我找不到对表示视图的实体进行建模的方法。我可以做的是向

Post
添加另一个关系并将
ViewPost
链接到它,但是没有更简单的解决方案吗?

@OneToMany(mappedBy = "postView")
private List<PostComment> comments = new ArrayList<>();
jpa spring-data-jpa spring-data
1个回答
0
投票

嗯,PostComment.post 是 Post 类型,而不是 PostView 类型。另外,如果您为一个 Post id 加载了两个实例:Post 和 PostView。并且您在 Post.comments 中添加了评论,那么 JPA 应该对 PostView.comments 做什么就不清楚了。

我的建议是将PostView中的OneToMany更改为

@Entity
@Immutable
@Table(name = "view_post")
public class PostView {

    @Id
    private Long id;

    // other fields omitted...

    @OneToMany(updateable=false, insertable=false)
    @JoinColumn(name="post_id")
    private List<PostComment> comments;
}

免责声明:我没有尝试过。这只是我脑子里打出来的。不确定您是否需要“可更新=假,可插入=假”,但也许吧。

© www.soinside.com 2019 - 2024. All rights reserved.