我需要加载一个包含这么多 child 和 child 的 child 的非常大的对象列表。最好的方法是什么?
我正在使用 Oracle 11g 数据库并且我编写了以下方法,但它导致笛卡尔积(重复结果):
public IList<ARNomination> GetByEventId(long eventId)
{
var session = this._sessionFactory.Session;
var nominationQuery = session.Query<ARNomination>().Where(n => n.Event.Id == eventId);
using (var trans = session.Transaction)
{
trans.Begin();
// this will load the Contacts in one statement
nominationQuery
.FetchMany(n => n.Contacts)
.ToFuture();
// this will load the CustomAttributes in one statement
nominationQuery
.FetchMany(n => n.CustomAttributes)
.ToFuture();
// this will load the nominations but joins those two tables in one statement which results in cartesian product
nominationQuery
.FetchMany(n => n.CustomAttributes)
.FetchMany(n => n.Contacts)
.ToFuture();
trans.Commit();
}
return nominationQuery.ToList();
}
最佳答案
获取集合是一项困难的操作。它有很多副作用(如您所见,当获取更多集合时)。但即使获取一个集合,我们也会加载许多重复的行。
一般来说,对于集合加载,我建议使用批处理。这将执行更多的 SQL 查询……但不是那么多,更重要的是,您可以对根列表 ARNomination
进行分页。
请参阅:19.1.5. Using batch fetching 您可以找到更多详细信息。
您必须使用属性 batch-szie="25"
标记您的集合和/或实体。
xml:
<bag name="Contacts" ... batch-size="25">
...
流利:
HasMany(x => x.Contacts)
...
.BatchSize(25)
请在这里检查几个参数:
关于nhibernate - 如何在 NHibernate 中不重复加载关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20970680/