开发者

Unwanted behavior with NHibernate transactions

开发者 https://www.devze.com 2023-03-21 23:34 出处:网络
I have a ASP.NET MVC 3 application using NHibernate over a PostgreSQL database. There is an operation on my website which takes all entities (I call them units) and if they satisfy certain condition

I have a ASP.NET MVC 3 application using NHibernate over a PostgreSQL database.

There is an operation on my website which takes all entities (I call them units) and if they satisfy certain condition, it updates one of their property (column). This whole operation is enclosed within a transaction.

Today I encountered a problem where I noticed that sometimes, (exactly) one unit does not get updated during the operation, even though it should (it satisfies the required condition).

Now I found out that this is because in the same time there are a lot of other requests coming to the server, which are also dealing with the units (for this request, it is always one unit which is examined and, if needed, modified).

So in one thread I have this code running:

ISession session = sessionBuilder.GetSession();
using (ITransaction transaction = session.BeginTransaction())
{
    var unitsToBeUpdated = session.QueryOver<Unit>()
            .Where(x => x.Status == STATUS_TRANSLATED)
            .JoinQueryOver<UnitParent>(u => u.Parent)
            .JoinQueryOver<Document>(p => p.Document)
            .Where(d => d.Job == job);

    foreach (Unit unit in unitsToBeUpdated.List<Unit>())
    {
        unit.Status = STATUS_CONFIRMED;
        session.SaveOrUpdate(unit);
    }     

    transaction.Commit();
}

and in a second thread I get this code running (multiple times, each time for different unitId)

Unit unit;
using (ITransaction transaction = sessionBuilder.GetSession().BeginTransaction())
{
    unit = unitRepository.GetById(unitId);
}

using (ITransaction transaction = sessionBuilder.GetSession().BeginTransaction())
{                
    unit.LastCategory = statisticsHarvester.AddWords(job, unit);  
    unitRepository.Update(unit);              
    transaction.Commit();
}

In this second thread, the transaction opening is shown twice because in fact these two transactions are created in different functions.

So the requests go like

Request A started...

Request B(unitId = 0) started...
Request B(unitId = 0) finished

Request B(unitId = 1) started...
Request B(unitId = 1) finished

....

Request B(unitId = n) started...
Request A finished
Request B(unitId = n) finished

Request B(unitId = n+1) started...
Request B(unitId = n+1) finished

....

Maybe I don't fully get the whole world of transactions and concurrent access, but in this situation, should it not be impossible for the first thread to update just some units? I expected开发者_如何转开发 the whole transaction to roll back, had something gone wrong. What is the problem here?

Thank you.

EDIT: Finally I solved this with "dynamic update" feature in NHibernate - in my case the two requests do not modify the same field of the entity, so it is viable.


I guess your problem is in here:

Unit unit;
using (ITransaction transaction = sessionBuilder.GetSession().BeginTransaction())
{
    unit = unitRepository.GetById(unitId);
}

using (ITransaction transaction = sessionBuilder.GetSession().BeginTransaction())
{                
    unit.LastCategory = statisticsHarvester.AddWords(job, unit);  
    unitRepository.Update(unit);              
    transaction.Commit();
}

Here you do a read and then start a new transaction. Between the two transaction the unit can be changed in the database. In the second transaction you save the old unit back into the database. Last write wins here.

Rewrite the code like:

Unit unit;
using (ITransaction transaction = sessionBuilder.GetSession().BeginTransaction())
{
    unit = unitRepository.GetById(unitId); //Add lock mode in you getbyid function LockMode.Upgrade
    unit.LastCategory = statisticsHarvester.AddWords(job, unit);  
    unitRepository.Update(unit);              
    transaction.Commit();
}

You should also check your transaction level.

And a good pattern to implement is optimistic locking (if the transaction fails, log the error). If you have problems in your locking you will see errors in your logs, and be able to debug your code.

http://knol.google.com/k/nhibernate-chapter-10-transactions-and-concurrency#10%282E%296%282E%29%28C2%29%28A0%29Pessimistic_Locking


+1 for peer's answer. To minimize these kind of problems consider that a transaction should enclose one operation.

So in your "second thread" try to assemble as mush as possible in that one transaction because the operation is to update the LastCategory property of the given units:

using (ITransaction transaction = sessionBuilder.GetSession().BeginTransaction())
{
    foreach (Unit unit in unitRepository.GetByIds(unitIds) { //an array of unitIds or something similar
       unit.LastCategory = statisticsHarvester.AddWords(job, unit);  
       unitRepository.Update(unit);              
    }
    transaction.Commit();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消