Java Reference
In-Depth Information
Users regularly abandon sessions and you don't want to implement a lock
cleanup mechanism.
Now that you have gotten an overview of this pattern, let's take a detailed look at
how to implement it. We're not going to show any JDBC or i BATIS code since it
would look similar to the code you saw in the previous chapter. Instead, we'll
focus on how to implement this pattern using JDO and Hibernate.
13.3 Optimistic offline locking with JDO and Hibernate
One of the benefits of using a persistence framework such as JDO or Hibernate is
that it provides an optimistic locking mechanism that typically uses version num-
bers or timestamps to detect changed objects when it updates the database. In the
previous chapter, we described how it is used within a single database transaction
to prevent concurrent updates. In this section, you will learn how to use it to
implement the Optimistic Offline Lock pattern.
There are two ways you can use a persistence framework's optimistic locking
mechanism to implement the Optimistic Offline Lock pattern. You can either
store the version number or timestamp of the object being edited in the session
state, or you can use detached objects. Let's see how these two approaches work.
13.3.1
Using version numbers or timestamps
Implementing the Optimistic Offline Lock pattern with a version number or times-
tamp is very straightforward. When the application loads an object that it intends
to update in a later database transaction, it stores the object's version number or
timestamp in the session state in, for example, the HttpSession . Then, during the
database transaction that updates the object, the application loads the object from
the database and verifies that its current version number or timestamp is the same
as the one stored in the session state. They will be different if the object was
updated since it was originally read and the application will signal an error.
This approach is simple to implement because the persistence framework tracks
changes to objects and increments version numbers or updates timestamps. Domain
objects just need to define a method that returns the current version number or
timestamp. For example, the Order class could define a getVersion() method,
which returns the version number maintained by the persistence framework:
class Order {
private int version;
 
 
 
 
 
Search WWH ::




Custom Search