2020-06-28

Hibernate JPA @OptimisticLocking Example

@OptimisticLocking

The @OptimisticLocking annotation is used to specify the currently annotated entity’s optimistic locking strategy.

The four possible strategies are defined by the OptimisticLockType enumeration:

NONE
The implicit optimistic locking mechanism is disabled.

VERSION
The implicit optimistic locking mechanism is using a dedicated version column.

ALL
The implicit optimistic locking mechanism is using all attributes as part of an expanded WHERE clause restriction for the UPDATE and DELETE SQL statements.

DIRTY
The implicit optimistic locking mechanism is using the dirty attributes (the attributes that were modified) as part of an expanded WHERE clause restriction for the UPDATE and DELETE SQL statements.

OptimisticLocking

Used to define the style of optimistic locking to be applied to an entity. In a hierarchy, only valid on the root entity.

Versionless optimistic locking

Although the default @Version property optimistic locking mechanism is sufficient in many situations, sometimes, you need rely on the actual database row column values to prevent lost updates.

Hibernate supports a form of optimistic locking that does not require a dedicated "version attribute". This is also useful for use with modeling legacy schemas.

The idea is that you can get Hibernate to perform "version checks" using either all of the entity’s attributes or just the attributes that have changed. This is achieved through the use of the @OptimisticLocking annotation which defines a single attribute of type org.hibernate.annotations.OptimisticLockType.

There are 4 available OptimisticLockTypes:


NONE
optimistic locking is disabled even if there is a @Version annotation present

VERSION (the default)
performs optimistic locking based on a @Version as described above

ALL
performs optimistic locking based on all fields as part of an expanded WHERE clause restriction for the UPDATE/DELETE SQL statements

DIRTY
performs optimistic locking based on dirty fields as part of an expanded WHERE clause restriction for the UPDATE/DELETE SQL statements

Versionless optimistic locking using OptimisticLockType.ALL

Example : OptimisticLockType.ALL mapping example

@Entity(name = "Person")
@OptimisticLocking(type = OptimisticLockType.ALL)
@DynamicUpdate
public static class Person {

@Id
private Long id;

@Column(name = "`name`")
private String name;

private String country;

private String city;

@Column(name = "created_on")
private Timestamp createdOn;

//Getters and setters are omitted for brevity
}

No comments:

Post a Comment