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?
Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
uniqueResult() Convenience method to return a single instance that matches the query, or null if the query returns no results. Method Detail.
Hibernate Disjunction, is used to add multiple condition in SQL query separated by OR clause within brackets. To generate following query using Hibernate Criteria we need to use Disjunction. select this_.id as id0_0_, this_. username as username0_0_, this_.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With