JPA标准选择组中具有最大值的所有实例 [英] JPA Criteria select all instances with max values in their groups
本文介绍了JPA标准选择组中具有最大值的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用JPA 2 CriteriaBuilder
编写与以下查询等效的方法?
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
);
在JPQL中,此查询为:
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
)
推荐答案
这应该可以工作,其中contest
是基本的Integer属性,或者是指向另一个非基本实体的ManyToOne
属性.
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();
这篇关于JPA标准选择组中具有最大值的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文