views:

598

answers:

2

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.

Andrew

A: 

Two quick observations:

  1. The Grails Documentation 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
Ken Gentle
I've added all the appropriate methods to support the many-to-many associations. I know this because I can add ClientContacts with owners. The problem is in the retrieval -as highlighted above.I tried the eqId() search criteria but it ends up returning the exact opposite ClientContacts. I'm lost.
anschoewe
A: 

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)
Bill James
Unfortunately, when I use your above code... I get an error that "No signature of method: grails.orm.HibernateCriteriaBuilder.eqId() is applicable for argument types: (java.lang.Long) values: {123}".When I use idEq, as seen here: http://grails.org/Hibernate+Criteria+Builder, I get an empty list.
anschoewe