You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring JPA Repository实现去重计数:统计话题独立用户浏览量

用Spring Data JPA命名查询实现独立用户浏览量统计

嘿,这个需求完全可以通过Spring Data JPA的命名查询规则轻松实现,不用费劲写自定义SQL!

核心方法定义

你只需要按照JPA的命名规范定义方法,它会自动帮你生成对应的count(distinct user_id)查询。具体方法名应该是:

Long countDistinctUserIdByTopicId(Long topicId);

为什么这个方法有效?

Spring Data JPA会解析方法名的语义:

  • countDistinctUserId:表示统计**去重后的userId**的数量,对应SQL里的count(distinct user_id)
  • ByTopicId:表示查询条件是topic_id = ?,和你之前的countByTopicId逻辑完全匹配

完整Repository示例

把这个方法加到你的Repository接口里就可以直接用了:

public interface ViewRepository extends JpaRepository<View, Long> {
    // 原方法:统计总浏览次数
    Long countByTopicId(Long topicId);
    
    // 新方法:统计独立用户数
    Long countDistinctUserIdByTopicId(Long topicId);
}

这个方法会自动生成你需要的SQL:

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

完全符合你的需求,而且不用额外写@Query注解,保持了代码的简洁性~

内容的提问来源于stack exchange,提问作者Chyngyz Sagynov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:36:56