Video in progress

Strong Middle 🐻 Hibernate and JPA

If you can't add a `version` column to the table, how do you enable optimistic locking in Hibernate?

Hibernate has @OptimisticLocking(type = DIRTY) or ALL mode: the old values are added to the where part of the UPDATE instead of a version. DIRTY checks only the changed columns and works together with @DynamicUpdate. This is good for legacy schemas, but unreliable with a detached entity (merge).

📖 Answer

The situation: you're connecting to an old database, another team manages the schema, and you can't add a version column. But two users must not overwrite each other's work on the same record.

@Entity
@OptimisticLocking(type = OptimisticLockType.DIRTY)
@DynamicUpdate
class Contract {
    @Id Long id;
    String status;
    BigDecimal amount;
}

If status changes, the SQL looks like this:

update contract set status = ? where id = ? and status = ?   -- the old value

If 0 rows are updated, you get OptimisticLockException, just as with @Version.

The difference between DIRTY and ALL: DIRTY checks only the columns you changed. So if two people change different columns, both succeed, which is often exactly what you want. ALL puts every column in the where and treats any parallel change as a conflict.

Limitations:

  • the old values come from the snapshot in the persistence context. If the entity becomes detached and is then merge()d, Hibernate first reads the fresh state from the database, so the old state the client saw is lost and the conflict isn't detected. That is, this approach works well inside a single transaction, not in a long "conversation";
  • comparing float/double and large text columns in the where is risky or slow;
  • for null values Hibernate writes is null, but indexes don't help there.

If I can, I'll still fight to get a @Version column added, since it's the simplest and most reliable route.