我正在创建一个函数,其中我的应用程序将显示最喜欢的照片。

我有这个课

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中,我将如何查询此类任务?

最佳答案

哈芬特里这..但只是尝试...如果没有用,我会删除这个答案

select photoId, count(photoId) from UserLikedPhoto group by photoId order by count(photoid) desc

在此查询中,我们按photoid进行分组,因此1张照片id只会有1行。

UserLikedPhoto中可用此照片ID的次数将告诉我们该照片被点赞的次数...

我们正在按desc订购,因此最喜欢的将排在最前面。
您问您要先5还是10 ...所以您可以在select语句中使用前10或前5个sql子句

所以最终的SQL将是这样的...

select top 10 photoId, count(photoId) from UserLikedPhoto group by photoId order by count(photoid) desc

Hibernate确实也支持本机sql。

07-24 09:20