cartilla wrote:
Hello!
I need to update one single field in multiple rows in a table which fulfill some specific criteria. Right now I'm using CreateCriteria to get all affected rows and iterate through the list setting the field to it's new value and saying SaveOrUpdate. As I open and close the session for every query (here: SaveOrUpdate) this isn't very fast. Is there a better way to do this?
I don't know if there is a real performance boost, but usually in a situation like this I'll open a single unused session just for it's connection, then build the further sessions using it's connection, like so:
Code:
ISession super = sessions.OpenSession();
ISession load = sessions.OpenSession( super.Connection );
IList objs = null;
try {
objs = load...
}
finally {
load.Close();
}
ISession update = null;
foreach ( Object o in objs ) {
// ... do stuff to object
update = sessions.OpenSession( super.Connection );
try {
update.Update( o );
update.Flush();
}
finally {
update.Close();
}
}
super.Close();
With connection pooling, I'm not sure that's really saving any time, but it's what I use. Also, I only do this when there's a large number of updates to do (not really sure about a threshold, though; my "large" is pretty vague). If there's only a few objects, I wouldn't bother building a session for each update.
Obviously, if anyone knows that this is a particularly bad or superfluous pattern, let me know!
I suppose it would be nice to have an update available through HQL, but I think that is frowned upon in certain quarters, since the changes are supposed to be done through the business object framework. Still, there are times when the "quick and dirty" solution is handy.