nhibernate 集合集映射以避免使用 fetch join 进行 n+1 选择和重复行
我有一个对象表和对象别名表。
别名只是字符串的集合:
object.Aliases
如果我像这样映射集合:
<class name="Object" table="Object" lazy="false">
...
properties...
...
<set name="Aliases" table="Aliases" inverse="true" lazy="false" fetch="join" >
<key column="ObjectId" />
<element column="Name" type="String"/>
</set>
...
</class>
然后
session.CreateCriteria(typeof (T)).List<T>();
从获取所有对象的基本存储库中,返回每个别名的重复项。为什么?如何删除列表中的重复对象?
感谢大家抽出宝贵的时间。
编辑: 更新了映射...但这就是所有映射。 Aliases 没有自己的类,因为它只是一组需要加载到 ISet
I have a object table and object aliases table.
The aliases is just a set collection of strings:
object.Aliases
If I map the collection like this:
<class name="Object" table="Object" lazy="false">
...
properties...
...
<set name="Aliases" table="Aliases" inverse="true" lazy="false" fetch="join" >
<key column="ObjectId" />
<element column="Name" type="String"/>
</set>
...
</class>
then
session.CreateCriteria(typeof (T)).List<T>();
from base repository which fetches all objects, returns duplicates for each alias. Why? how can I get rid of the duplicate objects in the list?
Thank you all for your time.
EDIT:
Updated mappings... but that's all the mappings. Aliases doesn't have it's own class as it's just a set of strings that needs to be loaded into ISet<string> Object.Aliases
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我开始使用 NHibernate 时,我也对此感到困惑。这就是它的工作原理。由于映射包含
fetch="join"
,因此它在父表和子表之间使用 SQL JOIN,因此每个子表都会重复父数据。但是,您不会过滤掉父级的额外实例,而是返回一个集合,查询中每行一个对象。您需要表明您想要不同的对象。使用 ICriteria 语法,您可以将 Transformers.DistinctRootEntity 添加到查询中。请参阅使用 Criteria API 从 NHibernate 获取不同结果集?,以及其中提到的链接。
I was confused by this, too, when I started using NHibernate. That's how it works. Because the mapping includes
fetch="join"
, it's using an SQL JOIN between the parent table and the child table, so the parent data is repeated for each child. But then rather than filter out the extra instances of the parent, you get back a collection with one object per row in the query. You need to indicate you want distinct objects. Using ICriteria syntax, you can addTransformers.DistinctRootEntity
to your query.See Get Distinct result set from NHibernate using Criteria API?, and the link it mentions within.
对于 select n+1 问题,将
batch-size="10"
添加到您的映射中For the select n+1 problem add
batch-size="10"
to your mappings