【问题标题】:JPA and Hibernate: Count number of related entries in projectionJPA 和 Hibernate:计算投影中相关条目的数量
【发布时间】:2021-08-14 17:41:47
【问题描述】:

我有一个简单的一对多关系。一个Post 可以有多个Comments。我的目标是通过 id 和相关 cmets 的数量(计数)获取帖子。

我使用的是 Kotlin,所以所有代码都只是一个简化的演示

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;

    private String text;
 
    @OneToMany(
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<Comment> comments = new ArrayList<>();
 
    //Constructors, getters and setters removed for brevity
}
 
@Entity(name = "Comment")
@Table(name = "comment")
public class Comment {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String review;
 
    //Constructors, getters and setters removed for brevity
}

现在我需要获取带有 cmets 数量的 Post。我想到了使用 dto 投影。

public class PostWithCount {
    private Long id;
    private String title;
    private String text;
    private Long numberOfComments;
}

我构造了下面的jpql Query,但是不知道怎么统计cmets的个数。

@Query("select new my.package.PostWithCount(post.id, post.title, post.text, ???) from Post post left join post.comments comment where post.id = :id")

在不获取所有 cmets 并在 java 代码中计数的情况下,计算 cmets 的最佳方法是什么?除了 DTO 投影之外,我也愿意接受其他解决方案。

【问题讨论】:

    标签: spring hibernate jpa jpql projection


    【解决方案1】:

    使用聚合...

    select new my.package.PostWithCount(post.id, post.title, post.text, count(1))
    from Post post 
        left join post.comments comment 
    where post.id = :id 
    group by post.id, post.title, post.text
    

    【讨论】:

    • 如果 DTO 有更多字段或有多个聚合,你知道另一种方法吗?
    • 只需添加适当的参数和查询聚合。
    猜你喜欢
    • 2022-12-08
    • 2011-01-29
    • 2019-04-20
    • 2019-11-30
    • 2021-08-16
    • 1970-01-01
    • 2016-09-04
    • 2023-04-09
    • 2021-06-19
    相关资源
    最近更新 更多