【发布时间】:2021-05-21 19:45:07
【问题描述】:
一个字不知道怎么称呼,我来详细解释一下吧。
假设我的数据库中有以下表/模式:
并相应地遵循以下课程:
1.发帖
@Entity
@Table(name = "posts")
public class Post {
@Id
private Long id;
@Column(name = "text")
private String text;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
private Set<PostComment> postComments = new HashSet<>();
}
2.发表评论
@Entity
@Table(name = "post_comments")
public class PostComment {
@Id
private Long id;
@Column(name = "post_id")
private Long postId;
@Column(name = "user_id")
private Long userId;
@Column(name = "text")
private String text;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="post_id")
private Post post;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
3.用户
@Entity
@Table(name = "users")
public class User {
@Id
private Long id;
@Column(name = "some_attributes")
private String someAttributes;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<PostComment> postComments = new HashSet<>();
}
如何通过 PostComment 与用户一起发布帖子,以便在我的帖子实体中获得所有用户的评论:
@Entity
@Table(name = "posts")
public class Post {
....
//@ join with post_comments.user_id
private Set<User> users = new HashSet<>();
....
}
【问题讨论】:
标签: jpa spring-data-jpa persistence