I want to achieve concurrency check using nHibernate 3 using UnitOfWork pattern.
To be more precise:
I'm using timestap to version entity.
Here is my mapping file
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-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)
应该足够了。
我认为您应该使用session.Lock(entity,LockMode.Update)
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.