Java Reference
In-Depth Information
updates a row it verifies that the row has not been changed or deleted by a differ-
ent transaction since it was read. If it has, the transaction is typically rolled back
and retried. Performing the inexpensive check at update time prevents the other
transaction's updates from being lost. Moreover, the overhead of redoing a trans-
action is only incurred when a concurrent update is detected.
A JDBC/ i BATIS application must implement the optimistic locking mechanism
itself. But, as you will see later, using optimistic locking in a JDO or Hibernate
application is simply a configuration issue. The application loads and updates
objects as usual, and JDO and Hibernate take care of all the bookkeeping
required to implement optimistic locking.
Tracking changes to data
There are three ways an application or a persistence framework can determine
whether a row has been changed since it was read. The first option is to track
changes using a version column, which is incremented whenever the application
updates a row. The transaction determines whether a row has changed by simply
comparing current value of the version column with the value that was originally
read from the database. This is usually the best approach since it is relatively sim-
ple for the application to check and update a version column.
The second option is to use a timestamp column, which is updated whenever
the application updates a row. A transaction determines whether a row has
changed by comparing the current value of the timestamp column with the value
that was originally read from the database. This scheme is also quite simple to
implement, especially since tables often already have a timestamp column in
order to record when a user last updated a row. However, one problem with using
timestamps is that one transaction might overwrite another if the time interval
between the two updates is less than the granularity of the clock. Consequently, an
application should only use a timestamp column when working with a legacy
schema that already has one and it's not possible to add a version column.
The third option is to compare current values of the columns with their previ-
ously read values. The biggest advantage of using this approach is that it can work
with an existing legacy schema because it does not require the addition of either a
version or timestamp column. One drawback of this approach is that it makes the
SQL UPDATE statements more complex since, as we describe later, the WHERE clause
will contain a condition for every column. It must also handle null values cor-
rectly, which can be complicated. For example, I once discovered that one popu-
lar persistence framework could not compare blank strings correctly because in
 
 
 
 
Search WWH ::




Custom Search