3

MyGrailsアプリには次のドメインオブジェクトがあります

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

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

私のDBには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

ちなみに、上記のクエリからeager-loadingを削除すると、ProductType期待どおりに7秒が取得されます。私は何が欠けていますか?

4

1 に答える 1

4

このFAQを読む必要があります:Hibernateは、コレクションに対して外部結合フェッチが有効になっているクエリに対して個別の結果を返しません(個別のキーワードを使用している場合でも)?

積極的な読み込みを指定すると、お気づきのように、結果セットには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 に答える