In my previous post about optimizing NHibernate queries I presented a simple technique using joins or left joins. Here is another simple but useful trick.
Considering that we have these 2 entities:
here is one way of mapping the relation:
<many-to-one name="ClientAddress" column="AddressId" class="Address" cascade="save-update" lazy="false" />
When we load the client, we get one select for the client and one select for the address:
Let's add one more attribute to the mapping:
<many-to-one name="ClientAddress" column="AddressId" class="Address" cascade="save-update" lazy="false" fetch="join" />
Now we are getting only one select, which makes a left join between the client and the address:
Conclusion: Map foreign key relationships with fetch="join" in order to load related entities in the same select instead of separate selects.