not able to handle concurrency and throwing exception (NHibernate.StaleObjectStateException: Row was updated or deleted by another transaction)

41 views
Skip to first unread message

rakesh singh

unread,
Oct 21, 2019, 10:08:19 AM10/21/19
to nhusers

below method not able to handle concurrency and throwing exception (NHibernate.StaleObjectStateException: Row was updated or deleted by another transaction)

In hibernate xml i am using <version name="DBVersion" column="DBVersion" type="Int64" generated="never" unsaved-value="0"/>

        public void Save(Object o)
        {
            try
            {
                // Check to make sure a session has been started, if not open a new session
                if (_session == null)
                    _session = GetSession();

                // Connect to the DB if necessary
                ReconnectDBConnection();
                // Start a transaction
                BeginTransaction();
                // save
                _session.SaveOrUpdate(o);
                // commit
                CommitTransaction();
            }
            catch (NHibernate.StaleStateException e)
            {
                string msg = "DB Stale data error.  Reason: " + e.ToString();
            //show error message
                throw new ExceptionDatabaseStaleData(msg, e);
            }

Oskar Berggren

unread,
Oct 22, 2019, 5:16:01 AM10/22/19
to nhusers
Hi,

It's difficult to say for sure with just a small method like this taken out of context. The problem is likely in the interaction between different parts of your application.

I will say however that I'm very suspicious of your Save() method. I mean no offence, but to me it looks like a collection of antipatterns.

For example - the automatic retrieval of a new session if there isn't already one suggests to me that the application has no clear rule for when a session should exist or not and we cannot tell from the code when the session is closed.

A session must be immediately discarded if there is an exception while it is open otherwise it may contain corrupt state that can lead to later problems (including corrupting data in the database).

Also, a transaction is meant to contain a logical unit of work. Open/closing sessions and transactions should be done top-level when starting a logical operation - not inside a low-level "save-method".



--
You received this message because you are subscribed to the Google Groups "nhusers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nhusers+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nhusers/36bc7658-1965-4429-95a4-b8ed9b9451ab%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages