JPA Criteria select all instances with max values in their groups

前端 未结 1 2019

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

select * from          


        
相关标签:
1条回答
  • 2020-12-09 23:46

    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();
    
    0 讨论(0)
提交回复
热议问题