2

Is is possible to do automatic relation fetching in GORM / Grails?

class Person {
    static hasMany = [cars : Car]
}
class Car {
    static belongsTo = [owner : Person]
}

Then use this relation like:

person = Person.get(1);
person.cars.each() { print it; }
tshepang
  • 12,111
  • 21
  • 91
  • 136
Josh K
  • 28,364
  • 20
  • 86
  • 132

2 Answers2

3

You can enable eager fetching this way:

static mapping = {
   cars fetch: 'join'
}

See http://grails.org/doc/latest/ref/Database%20Mapping/fetch.html

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • Thanks, I had already seen this and was wondering why it wasn't working when I render is as JSON. It doesn't appear to work well with a JSON render, only outputting the class and ID. – Josh K Jan 16 '11 at 06:57
  • That's a performance optimization and has nothing to do with eager or lazy loading. It'd be the same with lazy since the OpenSessionInViewInterceptor would lazily load the collection. Grails does this to avoid serializing large amounts of unexpected data. I tend to build a List of Maps from domain objects so I control what goes to the client, but it's more work than just "render foo as JSON". But you can use the deep converters to get what you want, e.g. http://manbuildswebsite.com/2010/02/08/rendering-json-in-grails-part-2-plain-old-groovy-objects-and-domain-objects/ – Burt Beckwith Jan 16 '11 at 16:53
0

The answer is: Yes, that works.

But I recommend reading the GORM Gotchas, to fully understand the basics of Hibernate under Grails' hood. Or sometimes you will see "surprisingly" behavior.

Hoàng Long
  • 10,746
  • 20
  • 75
  • 124