在另一个实体中通过id查找grails GORM

Mis*_*r B 0 grails grails-orm

我在grails映射中有2个实体

产品和资产

我需要获得产品ID等于x且资产类型等于y的资产

我试过了

Asset.findByProductIdAndAssetType(productId, assetType) 
Run Code Online (Sandbox Code Playgroud)

但不起作用

独特的解决方案是

按ID加载产品,按产品加载查找

def product = Product.findById(productId)
Asset.findByProductAndAssetType(product, assetType) 
Run Code Online (Sandbox Code Playgroud)

有没有办法只使用productId加载资产?

Bur*_*ith 6

使用此load方法通过一个数据库调用执行此操作:

Asset.findByProductAndAssetType(Product.load(productId), assetType)
Run Code Online (Sandbox Code Playgroud)

load()类似于get()它通过其id检索单个实例,但load()只有在访问除id之外的任何持久属性之后,才会懒惰地检索实例.get()立即进行数据库查询并返回实例,null如果没有找到,但load()始终返回非空代理,当它确实进行数据库查询时,如果找到则将从检索到的数据中填充其属性,否则抛出异常.

但是在上面的解决方案中,没有数据库调用Product实例,因为检索它所需要的Asset只是用作外键的id.