Efficiently retrieve objects with one to many references in Grails using GORM
- by bebeastie
I'm trying to determine how to find/retrieve/load objects efficiently in terms of a.) minimizing calls to database and b.) keeping the code as elegant/simple as possible (i.e. not writing hql etc.).
Assume you have two objects:
public class Foo {
Bar bar
String badge
}
public class Bar {
String name
}
Each Foo has a bar and a badge. Also assume that all badges are unique within a bar. So if a Foo has a badge "4565" there are no other Foos that have the same badge # AND the same bar.
If I have a bar ID, how can I efficiently retrive the Foo w/o first selecting Bar?
I know I can do this:
Foo.findByBadgeAndBar("4565", Bar.findById("1"))
But that seems to cause a select on the Bar table followed by a select on the Foo table. In other words, I need to produce the Grails/Hibernate/GORM equivalent of the following:
select * from foo where badge="4565" and bar_id="1"