【问题标题】:NHibernate Hierarchichal data fetching with single queryNHibernate Hierarchichal 使用单个查询获取数据
【发布时间】:2011-04-05 17:48:13
【问题描述】:

我在 DB 中有一个表,其中的列如下所示。

Id   Name     Publisher          ParentId
------------------------------------------    
100  Sample1  ExamplePublisher   NULL
200  Sample2  ExamplePubl3       100

NHibernate 映射如下。

   <class name="PaperMaster">
        <composite-id>
            <key-property name="Id"></key-property>
            <key-property name="AreaId"></key-property>
        </composite-id>       
        <property name="Name"></property>
        <property name="Parent"></property>
        <property name="Publisher"></property>
        <property name="YearStarted"></property>
        <bag name="ChildCollection" table="PaperMaster" lazy="false" 
                  inverse="true">
            <key>
                <column name="Parent"></column>
                <column name="AreaId"></column>
            </key>
           <key column="Parent"></key>
            <one-to-many class="PaperMaster"></one-to-many>
        </bag>        
        <many-to-one name="ParentObject" column="Parent">
            <column name="Parent"></column>
            <column name="AreaId"></column>
        </many-to-one>        

    </class>

当我像下面这样查询 NHIbernate 时,我成功地获取了正确填写子集合的对象。

   IList<PaperMaster> allList = se.CreateQuery("select e from PaperMaster e join fetch
      e.ChildCollection where e.Id=100")
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .List<PaperMaster>();

我面临的问题是每个孩子都会运行一个查询来填充似乎非常昂贵的对象。有没有办法简化这个?例如,在单个查询中,我应该能够获得完整的关系。

【问题讨论】:

标签: nhibernate nhibernate-criteria


【解决方案1】:

减少查询量的一种方法是在您的包映射中添加batch-size="25"

例如

 <bag name="ChildCollection" table="PaperMaster" lazy="false"
     batch-size="25" inverse="true">

这将大大减少查询量。

【讨论】:

  • 感谢您的建议。这会在 Web 场中成功运行吗?这是我们最大的担忧,因为我们没有状态服务器。
  • 我不知道为什么这不起作用。您仍然会从一台 Web 服务器获得多个查询,但不是 100 个,而是 4 个(即 batch-size="25"
  • 基本上每 25 个查询就有 1 个查询,因此选择 n+1 问题不大。
  • 很抱歉将网络农场称为问题。我通过在 MVC 中的 OnActionExecuting 和 OnActionExecuted 事件中打开会话并关闭来克服了这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多