6

有没有办法用 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
)
4

1 回答 1

18

这应该contest可以作为基本整数属性或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();
于 2013-01-18T21:00:37.050 回答