nhibernate collection set mapping to avoid n+1 select and duplicate rows with fetch join
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 开发者_Python百科class as it's just a set of strings that needs to be loaded into ISet<string> Object.Aliases
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 add Transformers.DistinctRootEntity
to your query.
See Get Distinct result set from NHibernate using Criteria API?, and the link it mentions within.
For the select n+1 problem add batch-size="10"
to your mappings
<set name="Aliases" batch-size="10" ...
精彩评论