How to create criteria in groovy/grails for nested object?
Asked Answered
P

1

12

I need help on creating hibernate criteria for nested object. For example :

class office{
    Integer id;
    OfficeDetails cmdData ;
}

class OfficeDetails {
    Integer id;
    Region region;

}

class Region {
    Integer id;
    Integer regionNum;
}

Now, from the service class ( officeService) I am trying to pull up all of the offices that matches a certain region as :

List<Office> findAllByRegion( Integer regionNumber){
    def criteria =  {  eq ( 'cmdData.region.regionNum', regionNumber ) }
    def allOfficesInTheRegion =  Office.findAll(criteria)

    return allOfficesInTheRegion
}

Always getting exception :"org.hibernate.QueryException: could not resolve property:" I need to find out right way to create criteria for this query.Can anyone help?

Prothorax answered 17/10, 2012 at 15:48 Comment(0)
C
16

See "querying associations" under the criteria section of the user guide:

def criteria = {
  cmdData {
    region {
      eq('regionNum', regionNumber)
    }
  }
}
Carbo answered 17/10, 2012 at 15:54 Comment(1)
For my and others benefit copying the working code: def criteria = MyOffice.createCriteria(); def results = criteria.list { cmtData { region { eq("regionNum", regionNumber) } } }; return results;Prothorax

© 2022 - 2024 — McMap. All rights reserved.