开发者

nHibernate and concurrency check

I want to achieve concurrency check using nHibernate 3 using UnitOfWork pattern.

To be more precise:

  • open new session session,
  • load entity in a session,
  • close session,
  • give user some time to edit data in loaded entity,
  • open new session,
  • update data
  • close session.

I'm using timestap to version entity.

Here is my mapping file

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapp开发者_如何学运维ing-2.2"
                   assembly="...."
                   namespace="...."
                   default-lazy="false">    
  <class name="Employee"
         optimistic-lock="version"
               dynamic-update="true">
    <id name="Id">
      <generator class="native" />
    </id>
    <version column="LastEditDate" generated="always" type="timestamp" />
    <property name="Name" not-null="1" length="255" />
    <property name="LastEditUser" not-null="1" length="255"/>
  </class>    
</hibernate-mapping>

I have no idea how to update entity in session context

var entity = <updated by user>
using (var session = GetNewSession())
{
    //todo: load current version value / attach entity to context
    session.SaveOrUpdate(entity);
    //if concurency check fails, StaleObjectException (or similar) is expected to be thrown
}

In SQL it should work like this

UPDATE ENTITY SET LastEditDate = @P1, ... WHERE ID = @P2 AND LastEditDate = @P3

where:
@P1 - new LastEditDate
@P2 - entity ID
@P3 - previous LastEditDate

If ROWSMODIFIED = 1 then update was successfull, else if = 0 then ConcurrencyException

Using Linq2Sql it was very simple: create versioning column, attach entity to new session context and try to update.

How can I do it in nHiberate? Is it supported?


session.Update(entity)

should be enough.


I think you should use session.Lock(entity,LockMode.Update).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜