代码之家  ›  专栏  ›  技术社区  ›  Maurice Perry

休眠条件中的表达式

  •  6
  • Maurice Perry  · 技术社区  · 16 年前

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

    3 回复  |  直到 14 年前
        1
  •  9
  •   Catweazle    14 年前

    我认为您还可以使用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
  •  1
  •   Ori    16 年前

    这并不完全是你想要的,但是你可以使用“派生属性”来得到一些非常相似的东西。

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

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

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

    奥里

    冬眠 docs 包含有关此的详细信息。

        3
  •  1
  •   Matej    16 年前

    用标准来做是(可能)不可能的。但是 HQL 对这个有帮助。

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