[ACCEPTED]-Best type for JPA version field for Optimistic locking-optimistic-locking

Accepted answer
Score: 12

Just go with Long or Integer. BUT don't 9 go with int or long. In opposite to other 8 comment here, null value is expected when 7 entity was never persisted yet. Having int 6 or long might make Hibernate to think that 5 entity is already persisted and in detached 4 state as version value will be 0 when unset. Just 3 finished debugging a FK violation where 2 "int" was the cause, so save your time and 1 just go with Long or Integer.

Score: 5

First, know that locking is used to managed 13 concurrent transactions.

1.Separate your 12 concerns. If lastupdated field is business 11 model specific, it should be separate from 10 your versioning field - which is for - versioning.

2.Primitives 9 and objects are usually mapped to your db 8 as the same type. Except for the fact that 7 Boolean by default will be nullable and 6 boolean will be 'not nullable'. However, enforce 5 nullability explicitly. In this case you 4 want to use a primitive as the version field 3 can't be nullable.

Integer or long are better 2 than timestamp. Hibernate recommends numeric versionig and they don't take that 1 much space.

  1. If you use long, you might not live to find out.

Use this and you should be fine.

private long version;

@Version
public long getVersion() {
    return version;
}

public void setVersion(long version) {
    this.version = version;
}
Score: 0

Don't use a time value like Timestamp (or 11 derivates like Instant or LocalDateTime 10 etc...).

Especially if you have a Java < 15 9 application and hope to ever migrate to 8 Java >= 15. They changed the precision 7 of timestamps within Java to nano-seconds, but 6 your database probably only stores up to 5 microseconds, so it truncates the value, which 4 will make you run into an OptimisticLockException 3 all the time (1).

Neither use a primitive 2 value, see the answer from @Piotr: The Version 1 field must be null for new entities.

Just go with Long.

More Related questions