How can I convert following SQL query to NHibernate?
UPDATE MyTable
SET Field1 = "NewValue1",
Field2 = "NewValue2"
WHERE Field3 = FilterValue
Assume that MyTable
contains huge records and above statement affects good percentage of it. It have 50 fields (columns) and some of them hold long strings or reference to other table that I would avoid to load/update unnecessarily.
The way I implemented it now is as below:
entities = nhSession.QueryOver<T>().Where(whereJunction).List();
nhSession.SetBatchSize(batchSize);
transaction = nhSession.BeginTransaction();
foreach(entity in entities)
{
//Modify entity here...
//nhSession.Update(entity);//No need to call this. Commit() will do.
}
transaction.Commit();
Even though batching helps improve performance, this approach have following drawbacks:
- Multiple statements executed ultimately degrading performance.
- Long
foreach
loop. - Using
nhSession.Flush()
does not overcome the drawbacks.
Advantage is that, updates are reflected in cache.
Another way is HQL
that I am not considering for following reasons:
- Strings; I do not love them much. That is one of the reason I switched to
ORM
. - Not strongly typed. Refactoring is difficult.
- Updates are not reflected in cache.
- I am not sure if this honors UoW (NHibernate Transaction).
Yet another way is raw SQL
that I do not want to use. I want to stick to ORM.
References:
Link1: Question and all answers suggests the ways I have already mentioned above.
Link2: Same that I have already mentioned above.
Link3: Same that I have already mentioned above.
Note: I have also added 'hibernate' tag assuming similar solution will also available with NHibernate; they are twins by the way.