Java – Expressions in hibernate criteria


Let's say I have a persistent class Item with a quantity field and a price field.
Is there a way to build a Criteria that calculates the sum of quantity*price?

Best Solution

I think you can also use an SQL projection. It should be something like:

        .createAlias("item", "i") 
        .setProjection( Projections.projectionList() 
            .add( Projections.groupProperty("") ) 
            .add( Projections.groupProperty("i.price") ) 
            .add( Projections.groupProperty("i.quantity") ) 
            .add( Projections.sqlProjection( 
                    "price * quantity as total", 
                    new String[] { "total" }, 
                    new Type[] { Hibernate.DOUBLE }