简体   繁体   English

使用 Spring JPA 存储库进行不同计数

[英]Distinct counting with Spring JPA repository

Now I'm counting views of topic something like this:现在我正在计算这样的话题的观点:

Long countByViewOnTopicId(Long topicId);

This is equivalent to SQL query这相当于 SQL 查询

select count(*) from views where topic_id = ? 

This gives me the number of all views, but I need to count the number of unique users.这给了我所有视图的数量,但我需要计算唯一用户的数量。 I need JPA equivalent of below query:我需要相当于以下查询的 JPA:

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

I can use the @Query annotation, but I'm trying to write less custom SQL in the project.我可以使用@Query注释,但我试图在项目中编写较少的自定义 SQL。 Like below:像下面这样:

Long countDictinctUserIdByViewOnTopicId(Long topicId);

Update: `Below entry details:更新: `以下条目详细信息:

@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...

try this:尝试这个:

criteriaQuery.multiselect(criteriaBuilder.countDistinct(root));

https://en.wikibooks.org/wiki/Java_Persistence/Criteria https://en.wikibooks.org/wiki/Java_Persistence/Criteria

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM