急切加载递归关系 [英] Eagerly load recursive relation
问题描述
我有一个递归的一对多关系,它的默认惰性值为 true.我可以针对 NH API 编写哪些代码来有效地检索整个树,就像我在 SubCategories 映射上设置了 lazy="false" 一样?
I have a recursive one-to-many relationship that has the default lazy value of true. What code can I write against the NH API that will efficiently retrieve the ENTIRE tree AS IF I had lazy="false" on the SubCategories mapping?
这是递归的一对多关系:
Here's the recursive one-to-many relationship:
<class name="Category" lazy="false">
...
<list name="SubCategories" fetch="subselect">
<key column="ParentCategoryID"/>
<index column="PositionInList"/>
<one-to-many class="Category"/>
</list>
我没有在列表中指定 lazy="false",因为在我需要运行的大约一半的查询中需要惰性.我在列表中使用了 fetch="subselect" 作为优化,以便我设法检索整个树.
I don't specify lazy="false" on the list since laziness is required in about half the queries I need to run. I have fetch="subselect" on the list as an optimization for when I do manage to retrieve the entire tree.
我已经尝试过 ICriteria API:
I've tried the ICriteria API:
session.CreateCriteria<Category>().SetFetchMode( "SubCategories", FetchMode.Eager ).Add( Restrictions.IsNull("ParentCategory") ).SetResultTransformer( CriteriaSpecification.DistinctRootEntity ).List<Category>();
但那只是急切地加载层次结构中的第一级.
but that only eagerly loaded only the first level in the hierarchy.
推荐答案
参见 Ayende 的站点:有效地选择一棵树.我已经在我自己的应用程序中成功地使用了这种技术.使用 ICriteria,它看起来像这样:
See Ayende's site: Efficiently Selecting a Tree. I have successfully used this technique in my own applications. With ICriteria, it looks like this:
session.CreateCriteria<Category>()
.SetFetchMode("SubCategories", FetchMode.Join)
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.List<Category>()
.Where(x => x.ParentCategory == null);
此版本与您尝试过的版本之间的主要区别在于ParentCategory == null"过滤器的应用方式.为了检索整个树,它必须被排除在发送到数据库的查询之外——但我们仍然需要查询只返回树的根节点,所以我们将使用 linq 在数据库查询完成.
The main difference between this version and what you tried is how the "ParentCategory == null" filter is applied. It has to be left out of the query that is sent to the database in order to retrieve the whole tree - but we still need the query to only return the root nodes of the tree, so we'll use linq to find those after the database query has completed.
这篇关于急切加载递归关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!