开发者

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

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 pro开发者_开发技巧duce the Grails/Hibernate/GORM equivalent of the following:

select * from foo where badge="4565" and bar_id="1"


You could use criteria

    def c = Foo.createCriteria()
    def results = c {
        eq("badge", "4565")
        eq("bar.id", 1L)
    }

This results in a single select statement

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜