我刚开始玩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 profiler并查看此结果
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优化查询?我完全迷失了。
非常感谢您的支持。
答案 0 :(得分:2)
尝试添加batch-size
<bag name="Products" batch-size="25" ...>