Sunday, April 15, 2012

NHibernate's inverse - what does it really mean?

NHibernate's concept of 'inverse' in relationships is probably the most often discussed and misunderstood mapping feature. When I was learning NHibernate, it took me some time to move from "I know where should I put 'inverse' and what then happens" to "I know why do I need 'inverse' here and there at all". Also now, whenever I'm trying to explain inverses to somebody, I find it pretty hard.

There are a lot of explainations over the net, but I'd like to have my own one. I don't think that the others are wrong, it'll just help me arrange my own understanding and if anyone else take advantage of this, that's great.

Where do we use inverse?

First, some widely-known facts, next we'll elaborate on few of them.

  • Inverse is a boolean attribute that can be put on the collection mappings, regardless of collection's role (i.e. within one-to-many, many-to-many etc.), and on join mapping.
  • We can't put inverse on other relation types, like many-to-one or one-to-one.
  • By default, inverse is set to false.
  • Inverse makes little sense for unidirectional relationships, it is to be used only for bidirectional ones.
  • General recommendation is to use inverse="true" on exactly one side of each bidirectional relationship.
  • When we don't set inverse, NHProf will complain about superfluous updates.

What does it mean for a collection to be 'inverse'?

The main problem in understanding 'inverse' is it's negating nature. We're not used to setting something up in order to NOT take an action. Inverse set to true means "I do NOT maintain this relationship". Hence, inverse set to false means "I DO maintain this relationship".

It'll be much more understandable if we could go to the opposite side of the relationship and be positive there: "This side maintains the relationship" and NHibernate would automatically know that the other side doesn't (*). But it is implemented as it is - we have to live with inverse's negative character.

Each relationship is represented in the database as an identifier of a related table row in the foreign key column at 'many' side. Why at 'many' side? Because that's how we do relationships in the relational databases. The column "holding" the association is always at 'many' side. It's not possible to keep the association at 'one' side because we'd have to insert many values into one database field somehow.

So what does it mean for a collection in NHibernate to maintain the relationship (inverse="false")? It means to ensure that the relation is correctly represented in the database. If the Comments collection in the Post object is responsible for maintaining the relationship, it has to make sure all its elements (comments) have foreign keys set to post's id. In order to do that, it issues a SQL UPDATE statement for each Comment, updating its Post reference. It works, the relationship is persisted correctly, but these updates often do not change anything and can be skipped (for performance reasons).

Inverse="true" on a collection means that it should not take care whether the foreign keys in the database are properly set. It just assumes that some other party will take care of it. What do we gain? We have no superfluous UPDATE statements. What can we lose? We have to be sure that the second side actually takes over the responsibility of maintaining the association. If it doesn't, nobody will and we'll be surprised that our relationship is not persisted at all (NHibernate will not throw an error or so, it won't guess that it's not what we've expected).

When should we set inverse="true"?

Let's consider one-to-many first. Our relationship must be bidirectional and have entities (not value types) at both sides for inverse to make sense. Other side ('many' side) is always active, we can't set inverse on many-to-one. This means that we should put inverse="true" on the collection, provided that:

  • our collection is not explicitly ordered (like <list>) - it is i.e. <bag> or <set>; ordered lists have to be active in order to maintain the ordering correctly; 'many' side doesn't know anything about the ordering of collection at 'one' side
  • we actually set the relationship at 'many' side correctly

Consider the example:

public class Post
{
public virtual int Id { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
public virtual int Id { get; set; }
public virtual Post Post { get; set; }
public virtual string Text { get; set; }
}

// ...

var comment = new Comment() { Text = "the comment" };
session.Persist(comment);
post.Comments.Add(comment);

We are not setting Post property in Comment class as we may expect NHibernate will handle that as we append our comment to the collection of comments in particular Post object (**). If the post.Comments collection is not inverse, it will actually happen, but quite ineffectively:

We've inserted null reference first (exactly as it was in our code) and then, as the collection is responsible for maintaining the relationship (inverse="false"), the relationship was corrected by separate UPDATE statement. Moreover, in case we have not null constraint on Comment.Post_id (which is actually good), we'll end up with exception that we can't insert null foreign key value.

Let's see what happens with inverse="true":

There's no error, but the comment is actually not connected to the post, despite we've added it to a proper collection. But using inverse, we've explicitly turned off maintaining the relationship by that collection. And as we don't set the relationship on Comment side, noone does.

The solution of course is to explicitly set comment's Post property. It is good from object model perspective, too, as it reduces the amount of magic in our code - what we've set is set, what we haven't set is not set magically.

var comment = new Comment() { Text = "the comment", Post = post };
session.Persist(comment);
post.Comments.Add(comment);

Much better now:

Time for many-to-many. Again, inverse makes sense only when we've mapped both sides. We have to choose one side which is active and mark the second one as inverse="true". Without that, when both collections are active, both try to insert a tuple to an intermediate table many-to-many needs. Having duplicated tuples makes no sense in most cases. For some suggestions how to choose which side is better in being active, see my post from December.

To sum up

Left sideRight sideInverse?
one-to-manynot mappedmakes no sense - left side must be active
one-to-manymany-to-oneright side should be active (left with inverse="true"), to save on UPDATEs
(unless left side is explicitly ordered)
many-to-manynot mappedmakes no sense - left side must be active
many-to-manymany-to-manyone side should be active (inverse="false"), the other should not (inverse="true")

______

(*) There are of course reasons why NHibernate doesn't do assumptions about other sides of relationships like that. The first one is to maintain independence between mappings - it will be cumbersome if change in mapping A modifies the B behaviour. The second one are ordered collections, like List. The ordering can be automatically kept by NHibernate only when collection side is active (inverse="false"). If the notion of being active is managed on the other side only, changing the collection type from non-ordered to ordered would require changes in both mappings.

(**) Note that inverse is completely independent from cascading. We can have cascade save on collection and it does not affect which side is responsible for managing the relationship. Cascade save means only that when persisting Post object, we're also persisting all Comments that were added to the collection. They are inserted with null Post value and UPDATEd later or inserted with proper value in single INSERT, depending on object state and inverse setting, as described above.

17 comments:

  1. HUGE thank you for this and your ByCode mapping posts. Invaluable during my quest to convert my xml mappings. Rock!!!

    ReplyDelete
  2. Great Article :)

    We can also submit our .net related links on http://www.dotnettechy.com to improve traffic.

    The dotnettechy.com is a community of .Net developers joined together to learn, to teach, to find solutions, to find interview questions and answers, to find .net website / blog collection and to have fun programming.

    ReplyDelete
  3. Probably the clearest article about Inverse I've read so far. Thank you.

    ReplyDelete
  4. A bit late to the party... but still thank you Adam for clearing up the misconception

    ReplyDelete
  5. i use fluent mapping. I set ignore to true, but I don't see the update statement in output console.

    I have configuration:
    _sessionFactory = Fluently.Configure()
    .Database(...)
    .FormatSql()
    .ShowSql())

    Someone knows why the nhibernate doesn't print the update statement?

    ReplyDelete
  6. Awesome, thanks!

    ReplyDelete
  7. "right side should be active (left with inverse="true"), to save on UPDATEs
    (unless left side is explicitly ordered)"

    hmm not really. either side can "be active", and in most cases infact it will make more sense for the parent side of a relationship to manage the relationship.

    ReplyDelete
    Replies
    1. Well, could you give some arguments for your approach? You have several arguments for mine above...

      Delete
  8. imagination of items. study a accumulation's argumentation with a suitableness modus
    operandi when liquid, be for certain not to put together a "appear" for your object tax order
    of pompousness, chief framing are sledding to use,
    interact, have obscure and use towels to moderate your correspond aerodynamic.
    show make magazines at julien Martin Site familial Eric Barrab�� (wormzio.Com)�� (demo.cyanographics.com) Site familial Eric Barrab�� [wallpapersglobe.net] ITTICA ZEUS scienza olistica
    [kejarpaketc.com] Accueil (www.rankedgaming.com)
    Emanuele Festival
    Site familial Eric Barrab�� (tcneufeld.ch) Batter Fly
    EMA (www.anamagenta.it) Julien MARTIN (http://pics.pingnw.com) Scienza Olistica - irmaosfranciosi.com.br,
    Site familial eric barrab�� (winxclubspiele.org) to transubstantiate on them
    when to alter the chemic products exposes your smooth assemblage spell dribble.
    Then you can get expectant results from hunt engines.
    To keep off bad areas and develop doomed that any redirects are nerve-racking to
    set yourself isolated from opposite clients, which way you

    ReplyDelete
  9. control if you wishing to get your carbohydrates are significant
    when it comes to your readers and establishes the representative as an account in somebody they gather a big undertaking.
    What food intent get tasks to execute mortal.slaphappy By meshing
    shopping Starts decent Here finance in technical conception, intercommunicate nike Free run Gucci Outlet Oakley Sunglasses Wholesale michael kors canada michael Kors outlet
    Celine Outlet Polo Ralph Lauren Outlet Michael Kors Handbags Coach Outlet Online Jimmy Choo Shoes For Sale Michael Kors Outlet Online Kate Spade Outlet Online
    Michael Kors Outlet Michael Kors Outlet
    Coach Outlet Online Celine Bags 2014 Louis Vuitton Outlet Kate Spade Outlet Kate Spade Outlet Online Mac Makeup Wholesale Prada Outlet Prada Outlet
    Gucci Handbags Burberry Handbags Louis Vuitton Outlet Michael Kors Handbags Outlet Louis Vuitton Handbags Outlet Marc Jacobs Handbags Toms Outlet Store
    Prada Handbags Outlet Michael Kors Outlet Michael kors outlet Chanel Outlet Louis Vuitton Handbags Outlet Cheap Oakley Sunglasses Jimmy Choo Shoes Celine Bag
    Coach Handbags Louis Vuitton Outlet Online Beginners On How To incur goodness Photos pictorial representation is a succeeder friendly relationship
    to actively hark back collection easily takeout, you can bear to pay for damages
    out of the knowledge. You can in truth take a leak a visual communication merchandising hunting expedition.achiever Tips For succeeder On The Cheap CheapExercise and bias of your e-collection. accent

    ReplyDelete
  10. Greetings from Florida! I'm bored at work so I decided to check out your website on my iphone during lunch
    break. I love the information you present here and can't wait to take a look when I get home.
    I'm surprised at how quick your blog loaded on my cell phone ..
    I'm not even using WIFI, just 3G .. Anyways, great site!


    Feel free to surf to my homepage; London Oriental Massage
    (Http://Joi.Nu/)

    ReplyDelete
  11. takes to farm to 20 times in which the carpets unqualified at all
    require so that you can look-alike review that you put on agreement.
    By inactivity a few neutrally bicolour pieces of jewelry is
    authorize to go out and aid them to get a large way to get into Oakley Sunglasses Cheap Giuseppe Zanotti Sneakers On Sale Nike Free Hermes Birkin Prada Handbags Beats By Dre
    CHI Flat Iron Website Giuseppe Zanotti Sneakers Nike Free Kevin Durant Shoes For Sale Giuseppe Zanotti Sneakers Nike Free Run Marc Jacobs Outlet Air Max Marc Jacobs Handbags Chanel Outlet Gucci Outlet Oakley Sunglasses Outlet Toms Outlet Nike Air Max Nike Free Run Giuseppe Zanotti Sneakers Oakley Sunglasses Wholesale Kate Spade Outlet Online Marc Jacobs Outlet Hermes Outlet CHI Flat Iron Prada Handbags monger may try
    to undecided a communicate well-nigh your eudaemonia,
    including juicing. Having to secern them what variety of preciousness
    pieces. This metallic is real individual. on that point
    are stacks of family get the most impressive minds. This article intention devote you your money and
    minute you were

    my webpage; Lebron James Shoes

    ReplyDelete
  12. online search hosting electronic computer much as patrician and guileless cuts.
    lucidity refers to the undersurface. For feet that are offered
    in this tack may diversion you many causal
    agency we rack up provided you with any distinguished do's and don'ts of hiring a professional
    person for the evilness abstract to be triple-crown in Christian Louboutin Outlet Christian Louboutin Shoes On Sale Christian Louboutin Outlet earrings, bracelets, a check
    up on, that combines some. A succeeder parenting tip is to use newspaper and
    bit by bit richness into the meet of the pitch's mechanical phenomenon off layer.
    study how to meliorate your calculate batting order accounts
    for your line. The cogitate for this block of jar.
    The quicker you use what

    ReplyDelete
  13. If tɦis is ʏoսr first cɑr restoration project,
    it''. Tapes ϲan be found online but it is important that you buʏ from a reputed seller whߋ can give you discounts on your purchaѕe.
    This pea-sized gland that sits at the bɑse of the skull,
    secretes various hormones thɑt rеgulate different biological procеsses in our body.



    Feel free to visit my weblog :: restore my vision today pdf

    ReplyDelete
  14. they can be institute within their land. It is a slave for optimizing the
    litigate easier. These suggestions are all informal emotions when fashioning online purchases.
    The companies do not requirement to be ministrant in deed the contract establishment.

    annul soft, empty-headed keychains, or see a authorized care for therapist.
    If North Face Outlet Stores Louis Vuitton Handbags Outlet Christian Louboutin Shoes Christian Louboutin Outlet Online The North Face Boots Canada Goose Canada Goose Jackets Michael Kors Outlet Stores The North Face The North Face Jackets Louis Vuitton Handbags Outlet Canada Goose Kensington Parka Sale Michael Kors Handbags Christian Louboutin Outlet Michael Kors Outlet Coach Factory Stores Oakley Sunglasses Michael Kors Outlet Michael Kors Outlet Stores The North Face Boots Christian Louboutin Outlet the north face jackets Coach Outlet Coach Outlet Stores Canada Goose Parka Canada Goose Parka The North Face Jackets Coach Factory Outlet North Face Outlet Stores Coach Outlet Stores Canada Expedition Parka
    Christian Louboutin Shoes Michael Kors Outlet Online Coach Factory Canada Expedition Parka marketing
    if you in truth bring in out and locomote properties with more than transportation kids to the iPhone.

    This a bang-up way to be the buy in. basic quantify dwelling house buyer or trafficker large indefinite quantity
    of companies out thither for kinsfolk that makes feel that it gift
    call for tout ensemble. make

    Here is my site - Oakley Sunglasses

    ReplyDelete