Search code examples
javahibernatecriteria

Hibernate Criteria Group by AND Order By


I need to put the next query into criteria

SELECT DISTINCT SUBSTRING(id, 1, LENGTH(id)-3) AS id_trunc, MAX(version) as version, MAX(code) as code
FROM theTable 
WHERE (version like '%.%' AND NOT version LIKE '%.0' AND event_code LIKE 'CODE1') OR (version LIKE '%.0' AND code LIKE 'CODE2')
GROUP BY id_trunc
ORDER BY id_trunc, version, code

I have exprience using Criteria but just for simple stuff, in this case I would need a way to do a projection, a Group By, and an Order By. I tried a few times but I couldn't make it work. I looked everywhere but I couldn't find any help for a query as complicated as this one.

This is what i have until now

    Criterion whereClause = Restrictions.and(Restrictions.like("version","%.%"), 
                            Restrictions.and(Restrictions.not(Restrictions.like("version","%.0")),Restrictions.like("code","CODE1")));

    Criterion secondWhere = Restrictions.and(Restrictions.like("Version","%.0"), Restrictions.like("code","CODE2"));
    LogicalExpression orWhere= Restrictions.or(whereClause,secondWhere);
    criteria.add(orWhere);

Solution

  • You have the restriction part right.

    So, to calculate your projection:

    criteria.setProjection(Projections.projectionList().
      add(Projections.groupProperty("SUBSTRING(id, 1, LENGTH(id)-3)", "id_trunc")).
      add(Projections.max("version")).
      add(Projections.max("code")))  
    

    Now to map your results you'll need another object, which will hold only three fields, and a transformer.

     criteria.setResultTransformer(Transformers.aliasToBean(TruncatedIdWithMaxVersion.class)) 
    

    And for the ORDER BY:

    criteria.addOrder(Order.asc("id_trunc"));