在多对多表Hibernate中计算ID的出现次数

时间:2013-04-28 12:07:53

标签: java hibernate java-ee many-to-many compound-key

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

我有这个班级

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

2 个答案:

答案 0 :(得分:0)

没有特权这个......但是试试......如果没有工作,我会删除这个答案

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。

答案 1 :(得分: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();