Skip Headers

# Optimistic Version Locking Policies

Previous

Next

With optimistic locking, all users have read access to the data. When a user attempts to make a change, the application checks to ensure the data has not changed since the user read the data.

Optimistic version locking policies enforce optimistic locking by using a version field (also known as a write-lock field) that you provide in the reference class that TopLink updates each time an object change is committed.

TopLink caches the value of this version field as it reads an object from the data source. When the client attempts to write the object, TopLink compares the cached version value with the current version value in the data source in the following way:

- If the values are the same, TopLink updates the version field in the object and commits the changes to the data source.

- If the values are different, the write operation is disallowed because another client must have updated the object since this client initially read it.

TopLink provides the following version-based optimistic locking policies:

- `VersionLockingPolicy`: requires a numeric version field; TopLink updates the version field by incrementing its value by one.

- `TimestampLockingPolicy`: requires a timestamp version field; TopLink updates the version field by inserting a new timestamp (this policy can be configured to get the time from the data source or locally; by default, the policy gets the time from the data source).

Note:

In general, Oracle recommends numeric version locking, because:

- accessing the timestamp from the data source can cause a performance issue

- time stamp locking is limited to the precision that the database stores for timestamps

Whenever any update fails because optimistic locking has been violated, TopLink throws an `OptimisticLockException`. This should be handled by the application when performing any database modification. The application must notify the client of the locking contention, refresh the object, and have the client reapply its changes.

You can choose to store the version value in the object as a mapped attribute, or in the cache. In three-tier applications, you typically store the version value in the object to ensure it is passed to the client when updated (see "Locking in a Three-Tier Application").

If you store the version value in the cache, you do not need to map it. If you do map the version field, you must configure the mapping as read-only (see "Configuring Read-Only Mappings").

To ensure that the parent object's version field is updated whenever a privately owned child object is modified, consider "Optimistic Version Locking Policies and Cascading".

When using optimistic version locking with the unit of work, consider "Using Optimistic Read Locking With forceUpdateToVersionField".