2013-04-28 42 views
0

我正在創建一個函數,其中我的應用程序將顯示最喜歡的照片。在多對多表中計數ID的出現休眠

我有這個類

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 
    } 

With this class。我將這種類型的表

------------------------------ 
| 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中,我將如何查詢這類任務?

回答

0

還沒有線索的..但只是嘗試...如果沒有工作,我會刪除這個答案

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

在此查詢,我們通過PHOTOID分組

所以只會有1排爲1張照片ID。

UserLikedPhoto提供照片ID多少次會告訴我們照片的喜歡數計...

我們正在遞減排序,以便用一個最想會在頂部。 你問你要第一個5年或10 ...所以你可以用前10名或前5 SQL子句中的select語句

所以最終的SQL會是這樣的......

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

Hibernate也支持原生sql。

+0

塞萊茨前10名?有這樣的事嗎?我不想手動手動計算所有照片。我想要的是一個查詢,它只會獲得某個ID最多的出現次數。 – user962206 2013-04-28 12:25:48

+0

更新回答 – 2013-04-28 17:21:59

+0

'top'子句似乎不起作用。它給我一個SQL語法錯誤 – user962206 2013-04-29 00:46:57

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();