gpt4 book ai didi

nhibernate - 急切获取引用时重复(多对一)

转载 作者:行者123 更新时间:2023-12-04 15:25:37 35 4
gpt4 key购买 nike

首先,是的,我使用的是 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 个 FifthObject。 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这解释了为什么会出现这种情况和解决方法。

Something that may not be apparent immediately is going to result in a Cartesian product. This is pointed out in the documentation, but I think that we can all agree that while there may be reasons for this behavior, it is far from ideal.

关于nhibernate - 急切获取引用时重复(多对一),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10320328/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com