Search code examples
javahibernatehibernate-criteria

Hibernate criteria Alias with projection minus second projection


I need to sort my grouped objects by the max field «timeStop» minus the min field «timeStart». Something like that :

ProjectionList projList2 = Projections.projectionList();
projList2.add(Projections.alias(Projections.max("timeStop") - Projections.min("timeStop"), "tim"));//Compilation error

Criteria criteria = sess.createCriteria(Call.class);
criteria.addOrder(up ? Order.asc("tim") : Order.desc("tim"));

How can i achive this?


Solution

  • Using sqlProjection

    Projections.projectionList()
                .add(Projections.sqlProjection("MAX(timeStop) - MIN(timeStop) AS tim",
                        new String[] { "tim" }, new Type[] {IntegerType.INSTANCE}));
    

    hibernate types can be found in the package org.hibernate.type