Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressions in hibernate criteria

Tags:

java

hibernate

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?

like image 926
Maurice Perry Avatar asked Jun 07 '09 08:06

Maurice Perry


People also ask

What is the criteria in Hibernate?

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.

What is criteria uniqueResult ()?

uniqueResult() Convenience method to return a single instance that matches the query, or null if the query returns no results. Method Detail.

What is disjunction in Hibernate criteria?

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


1 Answers

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

like image 52
Ori Avatar answered Sep 29 '22 03:09

Ori