现在我正在计算这样的主题观点:
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...
答案 0 :(得分:0)
尝试一下:
criteriaQuery.multiselect(criteriaBuilder.countDistinct(root));