Grails 3 - findAllBy 与加入

Grails 3 - findAllBy with join

我有一个域名class:

class Owner {
    Integer ownerType
    Prop propertyToJoinSometimes

    static constraints = {
        propertyToJoinSometimes nullable: true
    }
}

我通常不想在加载Owner时加载propertyToJoinSometimes,但有时我会使用findAllBy一次加载许多Owner对象,并且一次连接可以节省对数据库的大量调用。有没有办法做类似的事情:

Owner.findAllByOwnerType(2, [propertyToJoinSometimes: [fetch: 'join']])

这不是您要查找的内容(未使用动态查找器 findAllBy),但它会生成您想要的结果。 createCriteria/withCriteria 的 grails 文档没有提到它,但 HibernateCriteriaBuilder.

中有一个 fetchMode 方法
import org.hibernate.FetchMode   

Owner.withCriteria {
    eq('ownerType', 2)
    fetchMode('propertyToJoinSometimes', FetchMode.JOIN)
}

只需添加一个使用动态查找器的选项:

Owner.findAllByOwnerType(2, [fetch: ['propertyToJoinSometimes': 'eager']])