Exclusive locking in NHibernate

201 views
Skip to first unread message

FrederikGheysels

unread,
Apr 22, 2009, 4:32:03 AM4/22/09
to nhusers
In NHibernate, I want to retrieve an instance, and put an exclusive
lock on the record that represents the retrieved entity on the
database.

Right now, I have this code:

With.Transaction (session, IsolationLevel.Serializable, delegate
{
ICriteria crit = session.CreateCriteria (typeof
(TarificationProfile));

crit.SetLockMode (LockMode.Upgrade);

crit.Add (Expression.Eq ("Id", tarificationProfileId));

TarificationProfile profile =
crit.UniqueResult<TarificationProfile> ();

nextNumber = profile.AttestCounter;

profile.AttestCounter++;

session.SaveOrUpdate (profile);
});

As you can see, I set the LockMode for this Criteria to 'Upgrade'.
This issues an SQL statement for SQL Server which uses the `updlock`
and `rowlock` locking hints:

SELECT ... FROM MyTable with (updlock, rowlock)

However, I want to be able to use a real exclusive lock. That is,
prevent that others can read this very same record, until I have
released the lock.
In other words, I want to be able to use an `xlock` locking hint,
instead of an `updlock`.

I don't know how (or even if) I can achieve that .... Maybe somebody
can give me some hints about this :)

If it is really necessary, I can use the SQLQuery functionality of
NHibernate, and write my own SQL Query, but, I'd like to avoid that as
much as possible.
Reply all
Reply to author
Forward
0 new messages