JPA Criteria select all instances with max values in their groups

我怕爱的太早我们不能终老 提交于 2019-11-27 03:36:24

问题


Is there a way to write with JPA 2 CriteriaBuilder the equivalent of the following query?

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

In JPQL this query is:

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

回答1:


This should work, with contest being either a basic Integer property, or a ManyToOne property pointing to another non-basic Entity.

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


来源:https://stackoverflow.com/questions/14400532/jpa-criteria-select-all-instances-with-max-values-in-their-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!