Reputation: 1089
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
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
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
Reputation: 13357
Two quick observations:
eqId()
criterion - see createCriteriaUpvotes: 0