首先,是的,我正在使用 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 的引用)。
我有什么选择?我无法更改数据模型,但我确实需要全部加载。
提前致谢!