nhibernate - 如何在 NHibernate 中不重复加载关联?

标签 nhibernate orm future eager-loading cartesian-product

我需要加载一个包含这么多 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 QueryOver with Fetch resulting multiple sql queries and db hits
  • Is this the right way to eager load child collections in NHibernate
  • https://stackoverflow.com/q/18419988/1679310
  • 关于nhibernate - 如何在 NHibernate 中不重复加载关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20970680/

    相关文章:

    java - 如何在 Java 的 ExecutorService 中检索和处理异常

    asp.net-mvc - NHibernate与 Entity Framework [已关闭]

    symfony - 未定义索引 : inverseJoinColumns while trying to define ManyToMany relationship between two entities

    java - 当我执行 get 并抛出异常时,CompletableFuture 会自动取消吗?

    java - 对于这种情况,如何在 hibernate 中定义唯一约束?

    php - 在 Symfony2 中使用 Doctrine 映射异常错误

    scala - 在单独的执行上下文中运行断言的安全性

    NHibernate ByteCode 提供程序源

    c# - 以编程方式重新创建现有的sql server数据库?

    c# - 容器不处理 transient 组件