eager-loading queries with GORM/Hibernate

流过昼夜 提交于 2019-12-06 06:27:10

问题


My Grails app has the following domain objects

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

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

My DB has 7 ProductTypes and each of those has 3 Attributes. If I execute the query:

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

I expect 7 instances of ProductType to be returned, but in fact I get 21 (7 x 3). I understand that if I were to execute an equivalent SQL query to the above, the result set would have 21 rows

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

But I thought that when I retrieve these results via Hibernate/GORM I should get something more like:

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

Incidentally, if I remove the eager-loading from the query above, I get 7 ProductTypes as expected. What am I missing?


回答1:


you should read this 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)?

When you specify eager loading, the resultset contains, as you noticed, 7*3 rows but in fact you only have 7 productTypes objects in memory (& 2 extra references for each).
To do what you want, you can add (be aware that the underlying sql query did not change):

SetResultTransformer(new DistinctRootEntityResultTransformer())

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


来源:https://stackoverflow.com/questions/1436144/eager-loading-queries-with-gorm-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!