2009-06-07 73 views

回答

9

我想你也可以使用SQL投影。它應該是這樣的:

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

大利

+0

能否請你分不清哪裏是創建總的功能?這隻會創建產品。 – Victor 2011-05-16 15:52:20

1

這不完全是你要求的,但你可以使用「派生屬性」來獲得相似的東西。

例如,可以將totalPrice屬性映射到SQL表達式:

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

的SQL式「量*價格」被評估每實體被從數據庫中檢索的時間。

大利

Hibernate的docs包含有關此的詳細信息。

1

它可能(可能)不符合Criteria標準。但是HQL可以對此有所幫助。

SELECT ent.quantity*ent.price from EntityName as ent WHERE ent.id = ?