Search code examples
hibernategrailsgroovygrails-orm

Hibernate criteria - single object fetched


I'm working on a Grails project using Hibernate (GORM). I have the following Domain Models:

ClientContact {
   static hasMany = [owners: Person]
   static belongsTo = [Person]
}

Person {
   static hasMany = [clientContacts: ClientContact]
}

When I try to retrieve all the ClientContacts with a specific owner (Person), I'm running into some funny issues. I'm using the following query criteria:

def query = {
   owners {
      eq("id", Long.parseLong(params.ownerId))
   }
}
def criteria = ClientContact.createCriteria()
def results = criteria.list(params, query) 

The problem is when I iterate through each of my ClientContacts in the results, they only have the one owner - when in fact, most have many other owners. What gives? I know hibernate/GORM uses lazy fetching, but I thought it would fetch all of the other owners on a ClientContact when I tried to access them.

Any thoughts? I would like to continue using the list() function since it provides some nice paging features.


Solution

  • I know this thread is very old, but I just encountered exactly the same problem today and the solution seems to be usage of aliases, so instead:

    def query = {
            owners {
                    eq("id", Long.parseLong(params.ownerId))
            }
    }
    

    one can try:

    def query = {
            createAlias("owners", "o")
            eq("o.id", Long.parseLong(params.ownerId))
    }
    

    The first query creates left outer joins and the second creates inner joins. Please see this link for more detailed description: http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html