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?
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.
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.
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.
Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.
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.
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