简体   繁体   中英

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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