渴望在grails中获取整个对象树



所以我在域中有几个对象,它们之间存在hasMany关系,如下所示

Class Car {
    String name
    SortedSet tires = [] as SortedSet
    static hasMany = [tires: Tire]
}
Class Tire {
    String type
    SortedSet screws = [] as SortedSet
    static hasMany = [screws: Screw]
}
Class Screws {
     String type
}

现在,我想让整个对象树离线,为某种汽车,我可以通过findByName获得。我知道我们可以在寻找者身上进行抓取,但这只是一个层面。在这个例子中,我有两个或更多级别。

所以我的问题是。有没有一个优雅的解决方案可以急切地获取整个对象树,然后在没有grails/Hibernate触发另一个查询来获取详细信息的情况下四处使用它。

我尝试了以下几项,结果似乎相似,但都不太优雅。

withCriteria解决方案

def cars = Car.withCriteria {
    tires {
        screws {
            join 'screws'
        }
    }

此外,我还尝试将整个树转换为JSON并对其进行修复,但这似乎有些过头了。我想基本上我是想让整个对象树离线。如果这可以很容易或根本做到,你有什么想法吗?

TIA

使用映射闭包:

Class Car {
    String name
    SortedSet tires = [] as SortedSet
    static hasMany = [tires: Tire]
    static mapping = {
        tires lazy: false
    }
}
Class Tire {
    String type
    SortedSet screws = [] as SortedSet
    static hasMany = [screws: Screw]
    static mapping = {
        screws lazy: false
    }
}
Class Screws {
     String type
}

也许你应该像规则一样接受例外,我的意思是,你可以将你的域类配置为lazy: false,并用fetch lazy:调用你的finder

def cars = Car.findAllByType(type: "Alfa", [fetch: [tires: 'lazy']])

我不知道这是否是一个有效的选项,但你可以试试。

最新更新