sqlisolation-leveloptimistic-lockingsnapshot-isolation

optimistic lock with a "version" field vs snapshot isolation level


I was wondering what are the advantage/inconvenient for these two optimistic lock solutions :

  1. Use a "version" field and detect changes during updates (i.e. using hibernate @Version annotation)

  2. Use the Snapshot isolation level on transactions

If I'm correct these 2 solutions have the same behavior : an error will be thrown if the row has been updated during the transaction

Thanks


Solution

  • These two do not have the same behavior. With hibernate optimistic concurrency it is OK if the row to be written was modified in the meantime and modified back. For example a +1 followed by a -1. It is also OK that columns have been modified that hibernate does not check.

    Snapshot isolation checks all columns and does not compare data. Any write, even a null write such as x = x counts.

    Snapshot isolation also guarantees you a point-in-time snapshot for reads. You did not say what isolation level you intend to use for (1). I assume it's not SNAPSHOT. For that reason (2) is likely to offer you guarantees that hibernate cannot offer on its own.

    Hibernate optimistic concurrency is suitable for detached entities. Snapshot isolation cannot do that because it requires a transaction to encompass all operations you make.

    Note, that both solutions are not serializable since they verify writes but not reads.