Efficiently retrieve objects with one to many references in Grails using GORM

Posted by bebeastie on Stack Overflow See other posts from Stack Overflow or by bebeastie
Published on 2010-05-03T22:35:41Z Indexed on 2010/05/03 22:38 UTC
Read the original article Hit count: 256

Filed under:
|
|
|
|

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"

© Stack Overflow or respective owner

Related posts about grails

Related posts about gorm