C# – NHibernate additional UPDATE query run

cnhibernate

I have a many-to-many relationship defined between two entities using an association table and cascade="save-update".

Entity1 contains a list of Entity2, and conversely, Entity2 contains a list of Entity1. The SQL outputted from this worflow seems ok…

  1. Create an Entity1 and Entity2 object
  2. Add Entity2 to the List on Entity1
  3. Call session.Save on Entity1

-> Insert statements are run for both entities and then a record inserted into the association table linking them together.

However, if I first call session.Save on Entity2, add it to the List, then call session.Save on Entity1 there is an additional UPDATE statement run which sets all of Entity2's values to exactly the same as what was inserted at the start.

Although not causing any issues, it is an additional query reduce performance. I've played with the inverse attribute but this doesn't eliminate the extra update statement. Currently both sides have inverse="false" as I want the association table updated no matter which entity is saved.

Any ideas?

Best Answer

From the docs: inverse (optional - defaults to false): If enabled, Hibernate will not try to insert or update the properties defined by this join.

My suggestion: In some cases to prevent additional updates with 2-way joins BOTH collections may need to be updated:

Contact c;
Address a;    
c.Addresses.Add(a);
a.Contacts.Add(c);

You are probably getting the additional Update statement because both sides have inverse=false and the first entity's relationship list was saved empty. NH is only doing what it thinks it needs to in order to get all relationships updated.

Related Topic