【问题标题】:Expressions in hibernate criteria休眠条件中的表达式
【发布时间】:2009-06-07 08:16:29
【问题描述】:

假设我有一个带有数量字段和价格字段的持久类 Item。 有没有办法建立一个计算数量*价格之和的标准?

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    我认为您也可以使用 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 } 
                      ) 
                ) 
            ); 
    

    原产地

    【讨论】:

    • 你能告诉我创建总数的函数在哪里吗?这只会创建产品。
    【解决方案2】:

    这并不完全符合您的要求,但您可以使用“派生属性”来获得相当相似的东西。

    例如,您可以将 totalPrice 属性映射到 SQL 表达式:

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

    每次从数据库中检索实体时,都会计算 SQL 公式“数量 * 价格”。

    原产地

    Hibernate docs 包含有关此的更多信息。

    【讨论】:

      【解决方案3】:

      使用 Criteria (可能)不可能做到这一点。但是HQL 可以对此有所帮助。

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

      【讨论】:

      • HQL 更好
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      相关资源
      最近更新 更多