简体   繁体   中英

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);

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM