使用Spring JPA仓库进行不同计数

4
现在我正在统计类似这样的主题的浏览量:
Long countByViewOnTopicId(Long topicId);

这相当于SQL查询。
select count(*) from views where topic_id = ? 

这个查询可以给我所有浏览次数的数量,但我需要计算唯一用户的数量。我需要一个与下面查询等价的JPA查询:

select count(distinct user_id) from views where topic_id = ?

我可以使用@Query注解,但是我正在尝试在项目中减少自定义SQL的编写,像下面这样:
Long countDictinctUserIdByViewOnTopicId(Long topicId);

更新:以下是详细条目信息:
@Entity
@Table(name = "views")
public class Views {

    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    @Column(name = "user_id", insertable = false, updatable = false)
    private Long userId;

    @JoinColumn(name = "user_id")
    @ManyToOne
    private User user;

    @NotNull
    @Column(name = "topic_id", insertable = false, updatable = false)
    private Long topicId;

    @JoinColumn(name = "topic_id")
    @ManyToOne
    private Topic topic;

    @NotNull
    @Column(name = "action_type")
    @Enumerated(EnumType.ORDINAL)
    private ActionTypes actionType;

Getter, Setter...

3
我理解你的意思是 Long countDictinctUserIdByViewOnTopicId(Long topicId); 这个函数无法正常工作,这是否正确? - Syn
你能发布你的实体类吗?你的存储库的目标实体类是什么,它如何与用户连接?如果你的实体有一个User user字段,请尝试使用countDictinctUser而不是countDictinctUserId - Vladimir Vagaytsev
请查看 https://dev59.com/BVwY5IYBdhLWcg3w5rWq - Vladimir Vagaytsev
2
@Syn,也许应该使用countDistinctUserIdByViewOnTopicId来代替:-S - Aritz
@YCF_L 这是一个问题吗?文档中说可以使用派生计数查询:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/ 是否有关于distinct的案例参考? - Aritz
1
@XtremeBiker 我没有任何参考资料,我会在找到之前删除我的评论。 - Youcef LAIDANI
1个回答

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接