JPA Criteria选择其组中具有最大值的所有实例

时间:2013-01-18 14:01:41

标签: jpa jpa-2.0 criteria-api correlated-subquery

有没有办法用JPA 2 CriteriaBuilder写下相当于以下查询?

select * from season s1
where end = (
    select max(end)
    from season s2
    where s1.contest_id=s2.contest_id
);

在JPQL中,此查询是:

Select s1 from Season s1 
where s1.end = (
    select max(s2.end)
    from Season s2
    where s1.contest=s2.contest
)

1 个答案:

答案 0 :(得分:12)

这应该有效,contest可以是基本的Integer属性,也可以是指向另一个非基本实体的ManyToOne属性。

EntityManger em;      //to be injected or constructed

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Season> cq = cb.createQuery(Season.class);
Subquery<Date> sq = cq.subquery(Date.class);
Root<Season> s1 = cq.from(Season.class);
Root<Season> s2 = sq.from(Season.class);
sq.select(cb.greatest(s2.get(Season_.end)));
sq.where(cb.equal(s2.get(Season_.contest), s1.get(Season_.contest)));
cq.where(cb.equal(s1.get(Season_.end), sq));
List<Season> result = em.createQuery(cq).getResultList();