Grails criteria query with fetchMode eager with two levels
Asked Answered
Y

1

6

In my Grails project, I have the following classes:

class A {
    static hasMany = [cs:C]
}

class B {
    static hasMany = [cs:C]
}

class C {
    static belongsTo = [a:A, b:B]
}

I would like to query the class A and bring the all the associations from B and C eagerly. I tried the following criteria query, but when I iterate over Cs from A, hibernate uses lazy initialization to query B objects.

A.withCriteria() {
    fetchmode "cs", FetchMode.JOIN
    fetchMode "cs.b", FetchMode.JOIN
}

Any ideas?

Yeoman answered 16/5, 2012 at 20:57 Comment(0)
Y
9

Solved.

A.withCriteria() {
    cs{
        fetchMode "cs.b", FetchMode.JOIN
    }
}

Or

A.withCriteria() {
    cs{
        b{
        }
    }
}

In both cases Hibernate is using two queries. Much better than the 98 I had before ;-)

Yeoman answered 17/5, 2012 at 18:34 Comment(1)
i had a similar problem on one-to-many and the FetchMode.SELECT solved it for me.Caesium

© 2022 - 2024 — McMap. All rights reserved.