2020-06-28

Hibernate JPA @OptimisticLock Example

@OptimisticLock

The @OptimisticLock annotation is used to specify if the currently annotated attribute will trigger an entity version increment upon being modified.

OptimisticLock
Whether or not a change of the annotated property will trigger an entity version increment. If the annotation is not present, the property is involved in the optimistic lock strategy (default).

Excluding attributes

By default, every entity attribute modification is going to trigger a version incrementation. If there is an entity property which should not bump up the entity version, then you need to annotate it with the Hibernate @OptimisticLock annotation, as illustrated in the following example.

Example : @OptimisticLock mapping example

@Entity(name = "Phone")
public static class Phone {

@Id
private Long id;

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

@OptimisticLock( excluded = true )
private long callCount;

@Version
private Long version;

//Getters and setters are omitted for brevity

public void incrementCallCount() {
this.callCount++;
}
}

No comments:

Post a Comment