6

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?

Paul Morie
  • 15,528
  • 9
  • 52
  • 57
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97

3 Answers3

9

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

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

Ori

Catweazle
  • 619
  • 12
  • 25
Ori
  • 12,800
  • 4
  • 33
  • 32
  • Can you please tell where is the function that creates the total? This only creates the product. – Victor May 16 '11 at 15:52
1

It's not exactly what you asked for, but you can use "derived properties" to get something rather similar.

For example, you can map a totalPrice property to an SQL expression:

<property name="totalPrice" formula="quantity * price" type="big_decimal"/> 

The SQL formula "quantity * price" is evaluated every time the entity is retrieved from the database.

Ori

The Hibernate docs contain more info about this.

Ori
  • 12,800
  • 4
  • 33
  • 32
1

It is (probably) not possible to do it with Criteria. But HQL can be helpful for this.

SELECT ent.quantity*ent.price from EntityName as ent WHERE ent.id = ?
Matej
  • 6,004
  • 2
  • 28
  • 27