【问题标题】:NHibernate Linq. Querying associations and multiple sql queriesNHibernate Linq。查询关联和多个sql查询
【发布时间】:2011-01-23 21:13:06
【问题描述】:

我刚开始玩 NHibernate Linq,发现了一个奇怪的行为。我有一个类别类别和一个产品类别。类别有一个具有一对多关联的产品列表。这是映射:

  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="none" lazy="false" inverse="true" fetch="join">
      <key column="CategoryId" />
      <one-to-many class="Product" />
      <!--<filter name="IdFilter" />-->
    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>

当我使用此查询查询类别时

var cs = session.Query<Category>().Where(c => c.Products.Any(p => p.Price == 13.3392)).ToList();

我查看了 NHibernate 分析器并看到了这个结果

select category0_.Id   as Id1_,
       category0_.Name as Name1_
from   Category category0_
where  exists (select products1_.Id
               from   Product products1_
               where  category0_.Id = products1_.CategoryId
                      and products1_.Price = 13.3392 /* @p0 */)

SELECT products0_.CategoryId   as CategoryId1_,
       products0_.Id           as Id1_,
       products0_.Id           as Id0_0_,
       products0_.Name         as Name0_0_,
       products0_.Discontinued as Disconti3_0_0_,
       products0_.Price        as Price0_0_,
       products0_.CategoryId   as CategoryId0_0_
FROM   Product products0_
WHERE  products0_.CategoryId = 131073 /* @p0 */

SELECT products0_.CategoryId   as CategoryId1_,
       products0_.Id           as Id1_,
       products0_.Id           as Id0_0_,
       products0_.Name         as Name0_0_,
       products0_.Discontinued as Disconti3_0_0_,
       products0_.Price        as Price0_0_,
       products0_.CategoryId   as CategoryId0_0_
FROM   Product products0_
WHERE  products0_.CategoryId = 32768 /* @p0 */

类别是从数据库中一一获取的。因此,到数据库的往返次数等于 where 子句匹配的类别对象的数量。

有没有办法告诉 NHibernate 优化查询?我完全迷路了。

非常感谢您的支持。

【问题讨论】:

  • 你能发布完整的类别映射吗?
  • 我找到了从 linq 急切加载的更好解决方案。有兴趣的可以看看here

标签: nhibernate linq-to-nhibernate


【解决方案1】:

在你的包映射类上尝试添加batch-size

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

【讨论】:

  • 该死的,它成功了。你能告诉我背后的魔法是什么吗?或者,也许您可​​以向我提供一个描述批量大小行为的链接。谢谢谢谢,再次谢谢你:)
  • 查看bit.ly/ax2mik(休眠文档)了解更多信息。我建议阅读所有改进性能部分。 HTH。里波
  • 感谢 Rippo,感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多