Search code examples
hibernategrailsgrails-ormcriteriagrails-2.0

Check if domain class' hasmany collection contains the subset collection


Hello i'm trying to get list of domain objects if a domain object's hasmany association contains all elements in given list.

class Patient {
   static hasMany = [symptoms:Symptom]
}
class Symptom {
}

Looking for something similar to containsAll() but can be usable in criteria would be awesome. But i can't find it myself. I was hoping criteria would let me do this:

Patient.createCriteria().list {
    'containsAll'('symptoms',listOfSymptoms)
}

Solution

  • This can be done in HQL (less verbose) and yes there is no containsAll functionality in Criteria.

        Patient.executeQuery(
    "FROM Patient p WHERE p IN 
    (SELECT s.patient from Symptom s WHERE s.id = :id1) 
    AND p IN 
    (SELECT s.patient from Symptom s WHERE s.id = :id2) 
    AND p IN 
    (SELECT s.patient from Symptom s WHERE s.id = :id3)", 
    [id1: 1, id2: 2, id3: 3])