Search code examples
grailsgrails-orm

Request via dynamic finders in Grails


I've three domain classess:

class Cafee {

    String cafeeName

    static hasMany = [halls: HallsZones]

    static constraints = {
        halls nullable: true
    }
}

class HallsZones {
    String hallName

    static scaffold = true
    static hasMany = [table : TablePlacesInfo]
    static belongsTo = [cafee : Cafee]

    static constraints = {
        table nullable: true
        cafee nullable: true
    }
}

class TablePlacesInfo {
    int placesInTableAmount
    int tableAmount
    int tableForReservationAmount
    int placeCost
    String currencyType

    static scaffold = true
    static belongsTo = [hall: HallsZones]

    static constraints = {
        hall nullable: true
    }
}

As you can see, classess are connected with each other as via chain:

Cafee-(hasMany)->HallsZones-(hasMany)->TablePlacesInfo.

I want to get TablePlaces info, which has HallsZones as parent which in turn has a Cafee as parent. I know how to search by parent, for example:

def table = TablePlacesInfo.findWhere(hall : params['hallsAvailable'], placesInTableAmount : Integer.parseInt(params['tablePlacesAvailable'])) 

But how to search by grandparent too?


Solution

  • Using where query:

    TablePlacesInfo.where {
        hall {
            cafee {
                // criteria matching grand parent
                id == 1L // for example
            }
        }
    }.list()
    

    Using Criteria:

    TablePlacesInfo.withCriteria {
        hall {
            cafee {
                // criteria matching grand parent
                idEq 1L // for example
            }
        }
    }
    

    Using hql:

    TablePlacesInfo.executeQuery(
        """select tpi from TablePlacesInfo as tpi 
           inner join tpi.hall as hall 
           inner join hall.cafee as caf 
           where caf.id = 1"""
    )
    

    Choosing a DetachedCriteria or where would be a sound approach instead of dynamic finders.