I am working on the project which uses NHibernate. I don't keep session opened. When i need to get or save object, i open the session, do what i need and then close the session. So all the time i'm working with objects detached from session.
For example, when i need to get object from the database, i open the session, then call session.Get() and close the session. Then i update some properties of detached object. When i need to save changes to the database i call method that opens session, calls session.Update(myObject) and closes the session.
But when i do so, NHibernate generates sql that updates all the fields I have mapped, even though they have not changed. My suggestion is when objects is detached from session, NHibernate couldn't track the changes has been made. What approach do you use when you want to update only properties that has been changed for object detached from session? How do you track the changes for detached objects?
Thanks
The question is: why do you want to do this? I think it is not much of an optimization if you only update columns that have changed.
Have you got triggers in the database?
If so, you can do the following:
select-before-update="true"
and dynamic-update="true"
in the mapping. This makes NH to perform a query before the update and only updates if it changed, and only the columns that have changed. I'm not sure if it selects for every update, or only if it is not in the session.Merge
instead of update. This does actually the same: it selects the entity from the database, only if it is not already in the session. Also use dynamic-update="true"
. There is also a trade-off: Merge
returns the attached instance if there is already one in the session. So you should always throw away the instance you passed in and work with the instance you go from Merge
.Actually I wouldn't care about the updated columns. Its most probably faster to update them blindly instead of performing a preceding query.
Use dynamic-update="true" in the mapping.
Additionally to update detached object use this:
Session.SaveOrUpdateCopy(myObject)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With