简体   繁体   中英

NHibernate additional UPDATE query run

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 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. 调用session.Save,然后将其添加到列表中,然后再调用session.Save,然后将其添加到列表中,则在Entity1上将运行另一个UPDATE语句,该语句将Entity2的所有值设置为与开始时插入的值完全相同。

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?

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.

Thanks for the response but I believe I've found the problem. I had a repository class for each type of entity which implemented the CRUD operations. Each CRUD operation started it's own session/transaction, called Save/Update/etc then closed the transaction/session.

If I call the session.Save for Entity2 then session.Save for Entity1 (which contains the list of Entity2) NH seems to know that it has already persisted Entity2 in the session and hence doesn't try to update the record.

On the other hand, if I call session.Save for Entity2 then session.Save for Entity1 in a separate session/transaction it wants to update Entity2 again. I'm new to NH so not sure how it tracks which objects require updating, but it must reset between sessions?

Kinda makes my nice DDD repositories a little less useful though! Maybe the repositories should use a singleton session or something similar to avoid this problem?

Thanks, John

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM