Java Reference
In-Depth Information
environment, it is not unlikely that Client A will close a browser window on the open record,
never committing or canceling the transaction, so that the record remains locked until the
session times out. Clearly this is not a satisfactory solution. Usually, you will not want to
permit the alternative scenario, in which no locking is used, and the last person to save a
record wins!
The solution, versioning, is essentially a type of optimistic locking (see Chapter 8).
When any changes to an entity are stored, a version column is updated to reflect the fact
that the entity has changed. When a subsequent user tries to commit changes to the same
entity, the original version number will be compared against the current value—if they dif-
fer, the commit will be rejected.
The Hibernate/EJB 3 annotation mappings and the Hibernate XML-based mappings both
provide a simple syntax for indicating which field should be used for storing the managed ver-
sion information. The annotation for this field is shown in Listing A-5.
Listing A-5. Marking the Version Attribute Using Annotations
@Version
protected int getVersionNum() {
return versionNum;
}
The default optimistic locking strategy for Hibernate is versioning, so if you provide a
<version> element in your XML configuration, this will be used as long as you have enabled
dynamic updates (as shown in Listing A-6).
Listing A-6. Marking the Version Attribute Using XML Mappings
<class dynamic-update="version" optimistic-lock="version" ... >
...
<version name="versionNum"/>
</class>
The version attribute is defined in a very similar way to the normal property attribute
configuration. The version can be of type long , integer , short , timestamp , or calendar (note
that using the <timestamp ... /> element is an equivalent alternative to the use of the
<version type="timestamp" ... /> element syntax).
The <class> element's optimistic-lock attribute can be used to override the default
versioning-based optimistic locking strategy. You can disable it entirely (despite the pres-
ence of a version field) using a value of none . You can explicitly state that versioning should
be used with a value of version . You can elect to use dirty checking, with the dirty and all
options.
If you elect not to use versioning, dirty checking offers an alternative form of optimistic
locking. Here, the values of the entities are themselves checked to see if they have changed
since the entity was originally obtained. As with versioning-based optimistic locking, the
check against the database is carried out when the changes are committed. If an optimistic
lock type of dirty is selected, then only those fields that have changed since the persistent
entity was obtained will be checked (the Session keeps track of the appropriate state informa-
tion). If an optimistic lock type of all is selected, then all the fields comprising the entity will
Search WWH ::




Custom Search