[英]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.