Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can there be an if condition inside the Hibernate Create Criteria?

I am using HibernateCriteriaBuilder api to write my Criteria Queries. I want to know if inside Criteria we can have conditional logic, such as an if statement?

For example:

 OnemonthList=it.createCriteria().list {   
   if (res_id!='all'){
        eq('graresource',resourceInstance)
   }         
    between('currentdate', fromDate, toDate)         
    projections {       
    trans {
      countDistinct('id')    
    }
    groupProperty('currentdate')
        }                  
    } 

Is this valid?

like image 961
pri_dev Avatar asked Jan 30 '12 02:01

pri_dev


People also ask

Which is used for 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 restriction in hibernate criteria?

1.2. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method. This method takes an org. hibernate.

What is the difference between HQL and Criteria in hibernate?

HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries. HQL is to perform both select and non-select operations on the data, Criteria is only for selecting the data, we cannot perform non-select operations using criteria.

Is hibernate criteria deprecated?

Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.


1 Answers

Yes, you can use any sort of conditional or looping logic inside of the criteria DSL. Your example will work. Using loops can be incredibly useful, for example:

Domain.createCriteria().list {
    params.mapOfConditions.each {
        eq it.key, it.val
    }
}

will dynamically add an eq for each entry in the map that you have.

like image 149
doelleri Avatar answered Nov 13 '22 01:11

doelleri