Java 使用Spring JPA存储库进行不同计数
现在,我正在计算类似以下主题的视图:Java 使用Spring JPA存储库进行不同计数,java,spring,jpa,spring-data-jpa,Java,Spring,Jpa,Spring Data Jpa,现在,我正在计算类似以下主题的视图: Long countByViewOnTopicId(Long topicId); 这相当于SQL查询 select count(*) from views where topic_id = ? 这提供了所有视图的数量,但我需要计算唯一用户的数量。我需要相当于以下查询的JPA: select count(distinct user_id) from views where topic_id = ? 我可以使用@Query注释,但我试图在项目中编写更少的
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));
我假设
长countdictutuseridbyviewontopicid(长topicd)代码>不工作。对吗?你能发布你的实体类吗?回购协议的目标实体类别是什么?它是如何连接到用户的?如果您的实体有User-User
字段,请尝试使用CountDictionCtuser
而不是CountDictionCtuserID
查看@Syn,也许CountDistinCtuseridByViewWontoPicID
会:-S@XtremeBiker我没有任何参考资料,在找到之前我会删除我的评论