Avoid unnecessary select queries with join or left join, part 2

by andrei 26. September 2008 09:50

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:

ScreenHunter_01 Sep. 26 22.24

 

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:

image

 

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:

image

 

Conclusion: Map foreign key relationships with fetch="join" in order to load related entities in the same select instead of separate selects.

 

 

 

Enjoy programming!

 

I am putting together a set of concept lists for the main programming techniques, which should help developers learning or using them to be more efficient. Here are the techniques in progress:

Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

 

 

Also, if you are interested in learning these techniques you can try the developer training modules.

Again, please feel free to leave any comments or suggestions which could make the training modules more useful for everyone. We are having great results with them at Akcedo (so they really work), but they can always be improved. Also, if you would like to use the modules or are already using them and you want to discuss about the process feel free to comment and ask questions here.

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0