首先,是的,我正在使用DistinctRootEntityResultTransformer。
我有以下(Fluent NHibernate)映射:
public FirstObjectMap()
{
Id(x => x.Id):
HasMany<SecondObject>(x => x.SecondItems).KeyColumn("FirstObject_ID");
}
public SecondObjectMap()
{
Id(x => x.Id).Column("ID");
References(x => x.ThirdObject).Column("ThirdObject_ID");
}
public ThirdObjectMap()
{
Id(x => x.Id).Column("ID");
HasMany<D>(x => x.FourthItems).KeyColumn("ThirdObject_ID");
}
public FourthObjectMap()
{
Id(x => x.Id).Column("ID");
}
注意,SecondObject引用ThirdObject(意味着键在SecondObject上)。
我的查询如下所示:
var query = session.CreateQuery("select distinct first from " +
"FirstObject as first " +
"left join fetch first.SecondItems as second " +
"left join fetch second.ThirdObject as third " +
"left join fetch third.FourthItems as four where ...");
// This is not even needed as I'm using distinct in HQL
query.SetResultTransformer(new DistinctRootEntityResultTransformer());
var results = query.List<ReinsurableObject>();
为了进行测试,我在数据库中有1个FirstObject,1个SecondObject,1个ThirdObject和24个FourthObject。 SQL查询将返回预期的24行。
但是,这有个要点:NHibernate创建:
1 FirstObject
24 SecondObject (should be 1)
24 x 1 ThirdObject (should be 1)
24 x 1 x 24 FourthObject (should be 24)
因此,无论出于何种原因,NH都会创建24 SecondObject而不是1。
我猜想它不知道如何将“join fetch”(左侧或内部似乎无关紧要)映射到Reference(SecondObject中对ThirdObject的引用)。
我有什么选择?我无法更改数据模型,但是我确实需要急于加载所有数据。
提前致谢!
最佳答案
仅当加载父级和子级时,唯一根实体才有效。对于孙辈和曾孙辈来说,这是行不通的。问题是您正在加载多个集合关联并返回一个较大的cartesian product
请阅读此article by Ayende,它解释了为什么会出现这种情况以及解决方法。