有没有办法用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
)
答案 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();