Search code examples
javasqlhibernatecriteria

Simple HQL Query and Criteria in Hibernate


I have to write that HQL query:

FROM Sending adp WHERE adp.id = (SELECT MAX (adpw.id) FROM Sending adpw WHERE adpw.place = adp.place) 

I have to use Criteria API and I can't manage it. Query returns last sendings from all places in database and it works very well but now I have to transform it to Criteria. The only thing I managed is to show just one place with following code:

Criteria criteria = getSession().createCriteria(
                    Sending.class);
criteria.setFetchMode("place", FetchMode.JOIN);
DetachedCriteria maxId = DetachedCriteria.forClass(Sending.class).setProjection(Projections.max("id"));
criteria.add(Property.forName("id").eq(maxId));

Could you help me? Thanks in advance!!


Solution

  • Sorry for answering my own question, but I found the solution.

    I forgot that Subqueries can be correlated with themselves. I realized my query with following code:

    Criteria criteria = getSession().createCriteria(Sending.class);
    DetachedCriteria dc = DetachedCriteria.forClass(Sending.class, "adpw");
    dc.add(Restrictions.eqProperty("adpw.place", "adp.place"));
    dc.setProjection(Projections.max("id"));
    criteria.add(Property.forName("id").eq(dc));
    criteria.setMaxResults(count).setFirstResult(start);
    return criteria.list();
    

    Everything works now very well.