How do I perform Deep query in Grails using createCriteria

108 Views Asked by At

I have some grails Domain classes that have relationships between them like so...

Domain A {
    ...
    Domain B
}

Domain B {
    ...
    Domain C
}

Domain C {
    ...
    String name
    String attr1
    String attr2
}

How can I use withCriteria to perform eager fetching on A such that instances of B and C that are related to A are included in my results like so...

List<A> aList = [..., B: [..., C: [... name: 'name', attr1: 'attr1', attr2: 'attr2']]]
1

There are 1 best solutions below

2
Jeff Scott Brown On

The way you describe the expected results is a peculiar and I can't tell exactly what you want there...

List<A> aList = [..., B: [..., C: [... name: 'name', attr1: 'attr1', attr2: 'attr2']]]

The declared type of aList suggest you want a List<A> but the value you show looks like a Map with some nested Maps.

If you execute a query like this...

def aList = A.withCriteria {
    // your criteria goes here
}

What is returned from that will be a List of A and each A will reference a B and each B will reference a C.

def aList = A.withCriteria {
    // your criteria goes here
}

for(A obj : aList) {
    B b = obj.b
    C c = b.c

    // ...
}

I hope that helps.

EDIT BASED ON COMMENT:

It is unclear if you want them to always be eagerly fetched or if you want to express that when you express the query. It sounds like maybe you want to express it when you express the query, which can be done like this...

    import import org.hibernate.FetchMode

    // ...

    A.withCriteria {
        // criteria goes here

        fetchMode "b", FetchMode.JOIN
        fetchMode "b.c", FetchMode.JOIN
    }