Skip to content

Instantly share code, notes, and snippets.

@ppazos
Forked from roalcantara/sub_query.groovy
Created February 28, 2024 05:01
Show Gist options
  • Save ppazos/6f28aed64309acfc720c5d30fd38ec7e to your computer and use it in GitHub Desktop.
Save ppazos/6f28aed64309acfc720c5d30fd38ec7e to your computer and use it in GitHub Desktop.
Grails: Criteria + Subquery (DetachedCriteria)
/*
Suppose we need a query searching for all Equipments that are not being used in any ServiceOrder.
It means, given the following query:
select this_.*
from equipment this_
where this_.status == 'enabled'
and not exists (select so_.id as y0_ from service_order so_ where (so_.equipment_id=this_.id))
order by this_.serial_number asc;
*/
import org.hibernate.criterion.DetachedCriteria
import org.hibernate.criterion.Projections
import org.hibernate.criterion.Restrictions
import org.hibernate.criterion.Subqueries
def result = Equipment.createCriteria().list() {
eq 'status', 'enabled'
def subQuery = DetachedCriteria.forClass(ServiceOrder, 'so').with {
setProjection Projections.id()
add Restrictions.conjunction()
.add(Restrictions.eqProperty('so.equipment.id', 'this.id'))
}
add Subqueries.notExists(subQuery)
order 'serialNumber', 'asc'
maxResults(25)
cache: true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment