[英]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.