如何在NHibernate中避免重复的负载关联? [英] How to Eager Load Associations without duplication in NHibernate?

查看:80
本文介绍了如何在NHibernate中避免重复的负载关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加载包含很多孩子和孩子的孩子的非常大的对象列表.最好的方法是什么?

I'd need to load a list of very large objects with so many children and children of children. what's the best approach to take?

我正在使用Oracle 11g数据库,并且编写了以下方法,但是会产生笛卡尔积(重复结果):

I'm using Oracle 11g database and I've written the below method but it results in cartesian product (duplicated results):

 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();
        }

推荐答案

获取集合是一项困难的操作.它有很多副作用(如您所知,当获取更多集合时).但是即使获取了一个集合,我们仍在加载许多重复的行.

Fetching Collections is a difficult operation. It has many side effects (as you realized, when there are fetched more collections). But even with fetching one collection, we are loading many duplicated rows.

通常,对于集合加载,我建议使用批处理.这将执行更多的SQL查询...但是不是很多,更重要的是,您可以在根列表ARNomination上进行分页.

In general, for collections loading, I would suggest to use the batch processing. This will execute more SQL queries... but not so much, and what is more important, you can do paging on the root list ARNomination.

请参阅: 19.1.5.使用批量提取,您可以找到更多详细信息.

See: 19.1.5. Using batch fetching you can find more details.

您必须使用属性batch-szie="25"标记您的集合和/或实体.

You have to mark your collections and/or entities with an attribute batch-szie="25".

xml:

<bag name="Contacts" ... batch-size="25">
...

流利:

HasMany(x => x.Contacts)
  ...
  .BatchSize(25)

请在这里检查几个参数:

Please, check few arguments here:

  • 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中避免重复的负载关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆