Search code examples
hibernategrailsgrails-ormgrails-3.1

How to query on a many to many relationship in Grails?


I have the following Domain Classes:

class PreparedToWork {

    String location        
    static hasMany = [assessors: Assessor]        
}

class Assessor {

    //Some Properties

    static belongsTo = [PreparedToWork]     
    static hasMany = [preparedToWork: PreparedToWork]
}

I would like to retrieve all of the Assessors which are prepared to work in a certain location with only the prepared to work ID. I have my join table in the actual database so I'm certain the relationship is fine however have tried various querying options and have failed miserably.

App info:

  • Grails Version: 3.1.8
  • Groovy Version: 2.4.6
  • JVM Version: 1.8.0_60

Solution

  • I think the following is a much more natural way to describe your domain

    class Location {
    
        String name        
        static hasMany = [preparedToWork: Assessor]        
    }
    
    class Assessor {    
        //Some Properties
    
        static belongsTo = [Location]     
        static hasMany = [preparedToWork: Location]
    }
    

    Then you can retrieve all of the assessors who are prepared to work in a certain location with

    Assessor.executeQuery(
        "from Assessor a join a.preparedToWork l where l.id = ?", [locationId])