3

我的 Grails 应用程序具有以下域对象

class ProductType {
    String name
    static hasMany = [attributes: Attribute]
}

class Attribute {       
    String name
    static belongsTo = [productType: ProductType]
} 

我的数据库有 7ProductType秒,每个都有 3Attribute秒。如果我执行查询:

def results = ProductType.withCriteria {
    fetchMode("attributes", org.hibernate.FetchMode.EAGER)
}

我希望返回 7 个实例ProductType,但实际上我得到 21 (7 x 3)。我知道如果我要执行与上述等效的 SQL 查询,结果集将有 21 行

prod1 | attr1
prod1 | attr2
prod1 | attr3
..... | .....
..... | .....
prod7 | attr1
prod7 | attr2
prod7 | attr3
-------------
Total 21

但我认为,当我通过 Hibernate/GORM 检索这些结果时,我应该得到更像:

prod1 | attr1, attr2, attr3    
..... | ...................
..... | ...................
prod7 | attr1, attr2, attr3
---------------------------
Total 7

顺便说一句,如果我从上面的查询中删除急切加载,我会得到ProductType预期的 7 秒。我错过了什么?

4

1 回答 1

4

你应该阅读这个常见问题解答:Hibernate 不会为集合启用外连接获取的查询返回不同的结果(即使我使用 distinct 关键字)?

当您指定预加载时,结果集包含 7*3 行,但实际上您在内存中只有 7 个 productTypes 对象(每个对象有 2 个额外引用)。
做你想做的事,你可以添加(注意底层的 sql 查询没有改变):

SetResultTransformer(new DistinctRootEntityResultTransformer())

def results = ProductType.withCriteria {
    fetchMode("attributes", org.hibernate.FetchMode.EAGER)
    SetResultTransformer(new DistinctRootEntityResultTransformer())
}
于 2009-09-22T11:01:48.810 回答