NHibernate Hierarchichal data fetching with single query
I have a table in DB where columns are like below.
Id Name Publisher ParentId
------------------------------------------
100 Sample1 ExamplePublisher NULL
200 Sample2 ExamplePubl3 100
NHibernate mapping is like below.
<cl开发者_Python百科ass name="PaperMaster">
<composite-id>
<key-property name="Id"></key-property>
<key-property name="AreaId"></key-property>
</composite-id>
<property name="Name"></property>
<property name="Parent"></property>
<property name="Publisher"></property>
<property name="YearStarted"></property>
<bag name="ChildCollection" table="PaperMaster" lazy="false"
inverse="true">
<key>
<column name="Parent"></column>
<column name="AreaId"></column>
</key>
<key column="Parent"></key>
<one-to-many class="PaperMaster"></one-to-many>
</bag>
<many-to-one name="ParentObject" column="Parent">
<column name="Parent"></column>
<column name="AreaId"></column>
</many-to-one>
</class>
When I query NHIbernate like below I am successfully getting the object with child collections filled in properly.
IList<PaperMaster> allList = se.CreateQuery("select e from PaperMaster e join fetch
e.ChildCollection where e.Id=100")
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.List<PaperMaster>();
The problem I am facing is for each child a query runs to fill the object which seems to be very costly. Is there a way to simplify this? For example in a single query I should be able to get the full relation.
One way to reduce the amount of queries is to add batch-size="25"
on your bag mapping.
e.g.
<bag name="ChildCollection" table="PaperMaster" lazy="false"
batch-size="25" inverse="true">
This will reduce the amount of queries dramatically.
精彩评论