Video in progress

Strong Middle 🐻 Hibernate and JPA

Which type is good for a `@Version` field: `int`, `Long` or `Instant`? Why does this choice matter for Spring Data?

A numeric version (Long, Integer) is reliable: it goes up by exactly one on every UPDATE. An Instant version depends on time precision, and two changes can get the same timestamp. Choose a wrapper type, not a primitive: Spring Data decides an entity is new by version == null.

📖 Answer

@Version
private Long version;   // recommended

With a numeric version, where version = 3 and set version = 4 guarantee the conflict is detected. Short/Integer work too; Integer would take billions of updates to overflow, which isn't a problem in practice.

With a timestamp:

@Version
private Instant version;

This works too, and it looks convenient to combine it with a "last modified time". But the JVM clock and the precision of the database column (timestamp(3) or timestamp(6)) are limited, and two fast UPDATEs can get the same value. If the servers' clocks differ, it's worse still. I keep the version and updatedAt as separate fields.

The difference between primitive and wrapper matters for Spring Data:

@Version private long version;   // default 0

SimpleJpaRepository.save() decides whether an entity is new or existing with isNew(). If the version field is a wrapper, version == null means new, so persist(). If it's a primitive, Spring Data looks at the id; if the id was assigned by hand, it treats the entity as existing, calls merge(), and an extra SELECT shows up.

One more rule: don't change the version by hand. If you need to check a version that came from a DTO, don't write it onto the entity; compare it and throw OptimisticLockException yourself if they differ, because Hibernate manages the managed entity's version itself at UPDATE time.