views:

73

answers:

3

I have 2 tables in my database:

  • Category
  • BlogEntry

Each BlogEntry has 1 or more Categorys associated with it.

If I want to get a BlogEntry by its ID, I also want to get its Category information.

Maybe this example doesn't illustrate exactly a scenario where this would make sense, but say I want to load the Category ID and Name only, not all the other columns in the category database.

Would nHibernate load all the columns/properties for each entity?

A: 

It would depending on how you mapped it. Apparently bit code instrumentation can allow only partial tables to be retrieved but it is rarely needed.

Perhaps an explainantion of why you only want the id of the category...

If you define the hibernate mappings and instead of having the category an entity that maps to a category object just have it as an Integer. This is how i handle my mappings when i don't care about being able to fetch the attachments with my original queries.

Martin Dale Lyness
Why? Like I said, to avoid having to load columns that I don't need to display.
Blankman
A: 

You would want to look into Projections. We are actually using the AliasToBean transformer to get NHibernate to convert our projections directly into a screen specific DTO.

ShaneC
+1  A: 

I would handle this by mapping it as a one-to-many association between BlogEntry and Category so that BlogEntry has a collection of Category. I would set it so that the Category collection was lazy-loaded. I wouldn't care that I'm loading more columns than I will be displaying because I'm working with business objects and selecting by primary or foreign key. It's NHibernate's job to worry about that, though I would check up on it during development using SQL Profiler or NHProf.

NHibernate will load the collection by selecting Category records using the foreign key from BlogEntry. In almost all cases, there's no performance gain to be had by only returning the fields that you will be displaying. Retrieving business objects with only needed properties populated based on the display requirements is not a good object-oriented practice.

Jamie Ide