java 休眠条件中的表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/961480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:34:59  来源:igfitidea点击:

Expressions in hibernate criteria

javahibernate

提问by Maurice Perry

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?

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

回答by Ori

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

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

Ori

织里

回答by Ori

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:

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

<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.

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

Ori

织里

The Hibernate docscontain more info about this.

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

回答by Matej

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

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

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