2020-04-24

Hibernate JPA @Version Example

@Version

The @Version annotation is used to specify the version attribute used for optimistic locking.

Version Specifies the version field or property of an entity class that serves as its optimistic lock value. The version is used to ensure integrity when performing the merge operation and for optimistic concurrency control.
Only a single Version property or field should be used per class; applications that use more than one Version property or field will not be portable.

The Version property should be mapped to the primary table for the entity class; applications that map the Version property to a table other than the primary table will not be portable.

The following types are supported for version properties: int, Integer, short, Short, long, Long, java.sql.Timestamp.

    Example:

    @Version
    @Column(name="OPTLOCK")
    protected int getVersionNum() { return versionNum; }



@Version annotation mapping

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

@Id
@GeneratedValue
private Long id;

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

@Version
private long version;

//Getters and setters are omitted for brevity

}
@Entity(name = "Person")
public static class Person {

@Id
@GeneratedValue
private Long id;

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

@Version
private Timestamp version;

//Getters and setters are omitted for brevity

}
@Entity(name = "Person")
public static class Person {

@Id
@GeneratedValue
private Long id;

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

@Version
private Instant version;

//Getters and setters are omitted for brevity

}
Dedicated version number
The version number mechanism for optimistic locking is provided through a @Version annotation.

@Version annotation

@Version
private long version;
Here, the version property is mapped to the version column, and the entity manager uses it to detect conflicting updates, and prevent the loss of updates that would otherwise be overwritten by a last-commit-wins strategy.

The version column can be any kind of type, as long as you define and implement the appropriate UserVersionType.

Your application is forbidden from altering the version number set by Hibernate. To artificially increase the version number, see the documentation for properties LockModeType.OPTIMISTIC_FORCE_INCREMENT or LockModeType.PESSIMISTIC_FORCE_INCREMENT check in the Hibernate Entity Manager reference documentation.

No comments:

Post a Comment