问题描述
一字不知道怎么称呼,具体解释一下。
假设我的数据库中有以下表/模式:
并相应地遵循以下课程:
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 加入 Post with User,以便在我的 Post 实体中我可以让所有用户都评论:
@Entity
@Table(name = "posts")
public class Post {
....
//@ join with post_comments.user_id
private Set<User> users = new HashSet<>();
....
}
解决方法
好吧,只需获取 PostComment.user
,其中 PostComment.post
等于您的帖子。
@Query("select pc.user from PostComment pc where pc.post = :post")
List<User> getUsersWithComments(@Param("post") Post post);
似乎对我有用。给我以下 SQL:
Hibernate: select user1_.id as id1_2_,user1_.some_attributes as some_att2_2_ from post_comments postcommen0_ inner join users user1_ on postcommen0_.user_id=user1_.id where postcommen0_.post_id=?
我不知道这是怎么回事:
@Column(name = "post_id")
private Long postId;
@Column(name = "user_id")
private Long userId;
或者这个
@JoinColumn(name="user_id")
@JoinColumn(name="post_id")
你不应该这样做:
= new HashSet<>();
虽然我们这样做,但这是多余的。
fetch = FetchType.LAZY,