1

我正在创建一个功能,我的应用程序将显示最喜欢的照片。

我有这门课

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

4

2 回答 2

0

如果不进行测试,从一开始就很难做到这一点,但这是我的尝试:

Query q = session.createQuery("select p from 
    Photo as p, 
    (select ulp.pk.photo.photoId as photoId from UserLikedPhoto ulp 
           where ulp.date = :someDate group by ulp.pk.photo.photoId 
                 order by count(ulp.pk.photo.photoId) desc) as top 
    where p.photoId = top.photoId");
q.setParameter("someDate", new Date())
q.setMaxResults(10);
List<Photo> topPhotos = q.list();
于 2013-04-28T13:01:26.360 回答
0

没有尝试过这个..但只是尝试...如果没有工作我会删除这个答案

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

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

这张照片 ID 可用的次数UserLikedPhoto将告诉我们这张照片的点赞数……

我们是用 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。

于 2013-04-28T12:22:20.577 回答