JPA标准在他们的群体选择具有最高值的所有实例(JPA Criteria select all in

2019-07-18 09:24发布

有没有与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
)

Answer 1:

这应该工作,以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();


文章来源: JPA Criteria select all instances with max values in their groups