2009-09-17 118 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