我正在创建一个功能,我的应用程序将显示最喜欢的照片。
我有这门课
public class User{
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user", cascade = CascadeType.ALL)
private Set<UserLikedPhoto> likedPhotos = new HashSet<UserLikedPhoto>();
//Other properties and accessor methods.
}
照片类
public class Photo{
@OneToMany(fetch = FetchType .LAZY ,mappedBy = "pk.photo")
private Set<UserLikedTrack> likedByUsers = new HashSet<UserLikedTrack>();
//Other properties and accessor methods
}
CompoundId/CompoundObject
@Embeddable
public class UserLikedPhotoId implements Serializable {
@ManyToOne
private UserProfile user;
@ManyToOne
private Photo photo;
//Other Properties and accessor methods.
}
以及保存CompoundObject和日期的类
@Entity
@AssociationOverrides({
@AssociationOverride(name = "pk.userId", joinColumns = @JoinColumn(name = "userId")),
@AssociationOverride(name = "pk.photoid", joinColumns = @JoinColumn(name = "photoId")) })
public class UserLikedPhoto{
@EmbeddedId
private UserLikedPhotoId pk = new UserLikedPhotoId();
@Column
@Temporal(TemporalType.DATE)
private Date date;
//Other Entities and accssor methods
}
有了这个类。我将生成这种类型的表格
------------------------------
| date | UserId photoId |
-----------------------------
| 2010-12-23 | 1 | 23 |
| 2010-12-21 | 2 | 23 |
| 2010-12-23 | 1 | 24 |
| 2010-12-21 | 5 | 23 |
现在我想做的是获得示例中得票最多的照片(可能是给定日期的前 5 名或前 10 名),得票最多的照片是 23 号照片,第二多得票的是 24 号照片。
在 Hibernate 中我将如何查询此类任务?
最佳答案
还没有尝试过这个..但尝试一下...如果不起作用我会删除这个答案
从 UserLikedPhoto 组中选择 photoId、count(photoId) by photoId order by count(photoid) desc
在此查询中,我们按 photoid 进行分组,因此 1 个照片 ID 仅有 1 行。
此照片 ID 在 UserLikedPhoto
中可用的次数将告诉我们该照片的点赞数...
我们按照 desc 进行订购,因此最喜欢的将位于顶部。 你问你想要前5个还是前10个...所以你可以在select语句中使用前10个或前5个sql子句
所以最终的sql将是这样的......
从 UserLikedPhoto 组中按 photoId order by count(photoid) desc 选择前 10 个 photoId、count(photoId)
Hibernate 也允许支持 native SQL。
关于java - 统计Hibernate中多对多表中ID的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262685/