anschoewe
anschoewe

Reputation: 1089

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.

Upvotes: 3

Views: 2964

Answers (3)

Pawel Gwozdz
Pawel Gwozdz

Reputation: 46

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

Upvotes: 3

billjamesdev
billjamesdev

Reputation: 14642

id and version are special properties of all GORM classes. You don't need to specify them in the class declaration, and you can't use the standard criterion with them.

You definitely need to use the eqID criterion

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

Upvotes: 0

Ken Gentle
Ken Gentle

Reputation: 13357

Two quick observations:

  1. The [Grails Documentation](http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.3 Many-to-many) says that a many-to-many association has to be manually coded, the default scaffolding won't do it.
  2. You may need to use the eqId() criterion - see createCriteria

Upvotes: 0

Related Questions