Wednesday, 1 February 2012

JPA: How to implement Versioning (@Version)

In another article I will explain what versioning is and differences between optimistic and pessimistic versioning. Here I will just describe how to implement optimistic versioning it..

public class Foo {
 // ...

 prive Long version;
 public Long getVersion() { return version; }
 public void setVersion(Long version) { this.version = version; }

 // ...

On each transaction commit if the entity is modified (persist or merge) the version column is increased by one.

Other possibilities

Instead of a Long you could use a Integer or a Date..but Date has performance problems and does not guarantee good behavior if two commits are happened with milliseconds time difference (see

See also...

If you get StaleObjectStateException or OptimisticLockException then make sure that you don't persist the loading time of the entity (see
How to catch a OptimisticLockException

No comments:

Post a Comment