Given the following classic OneToMany
relationship between a blog post and its comments:
// 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;
}
Now, our database provides an additional view joining several other tables. Let’s call it view_post
. The list of post comments should be part of this view as modeled below:
@Entity
@Immutable
@Table(name = "view_post")
public class PostView {
@Id
private Long id;
// other fields omitted...
@OneToMany(mappedBy = "post")
private List<PostComment> comments;
}
This however doesn’t work as clearly indicated by the exception:
Association 'ViewPost.comments' is 'mappedBy' a property named 'post' which references the wrong entity type 'Post', expected 'ViewPost'
I cannot find a way to model the entity representing the view.