[英]JPQL complex One to Many join query result
我有两个简单的 DTO,
class Post{
@Id
private int postId;
private String text;
@OneToMany(mappedBy = "post")
private List<Comment> comments = new ArrayList<Comment>();
}
class Comment{
@Id
private int commentId;
private int userId;
private into text;
@ManyToOne
@JoinColumn(name = "postId")
private Post post;
}
现在,使用 JPQL,我想找到所有帖子以及用户评论,其中帖子包含给定用户的评论。
所以,基本上我想要一个“帖子”对象列表以及封装在每个帖子中的合格评论。
样本 SQL 可能如下所示:
select *
from post p
inner join comment c
on p.post_id = c.post_id
where c.user_id = {given user id}
public interface PostRepository extends CrudRepository<Integer, Post> {
@Query("select p from Post p inner join p.comments c where c.userId =:userId")
List<Post> findByCommentsUserId(@Param("userId") Integer userId);
}
Set<Post> posts = new HashSet<>(findByCommentsUserId("anyUserId"));
我写了这段代码但没有执行它所以它是伪代码但它会很相似
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.