2009-09-17 113 views
3

我的Grails应用急切装载查询具有下列域对象与GORM /休眠

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

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

我DB具有7个ProductType S和每个那些具有3 Attribute秒。如果我执行查询:

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

我期望返回的ProductType 7个实例,但事实上我得到21(7×3)。我明白,如果我执行等效的SQL查询以上,结果集将有21行

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

但我认为,当我通过休眠/格姆获取这些结果,我应该更喜欢得到的东西:

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

顺便说一句,如果我删除从上面的查询渴望加载,我得到7个ProductType S作为预期。我错过了什么?

+0

我已经注意到了这个自己,但那是我回来使用时Grails 1.0.4,你能指定你正在使用的Grails的版本吗? – billjamesdev 2009-09-21 01:48:32

+0

我正在使用版本1.1.1 – 2009-09-21 20:33:46

回答

4

要读这faq: Hibernate does not return distinct results for a query with outer join fetching enabled for a collection (even if I use the distinct keyword)?

当指定预先加载,结果集包含了,因为你注意到,7个* 3行,但实际上你只需要在内存中7个productTypes对象(每个& 2个额外的引用) 。
做你想做什么,你可以添加(注意,下面的SQL查询并没有改变):

SetResultTransformer(new DistinctRootEntityResultTransformer())

def results = ProductType.withCriteria { 
    fetchMode("attributes", org.hibernate.FetchMode.EAGER) 
    SetResultTransformer(new DistinctRootEntityResultTransformer()) 
} 
+0

很高兴它有帮助,谢谢。 – manji 2009-09-23 07:44:27