[英]Distinct counting with Spring JPA repository
現在我正在計算這樣的話題的觀點:
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...
嘗試這個:
criteriaQuery.multiselect(criteriaBuilder.countDistinct(root));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.