Video in progress

Strong Middle 🌱 Spring

What does Hibernate's @DynamicUpdate annotation do, and when is it useful and when harmful?

By default Hibernate writes all of an entity's columns in an UPDATE, and it prepares that SQL at startup. With @DynamicUpdate only the changed columns are written. That's useful on wide tables, but the SQL is rebuilt every time and the statement cache works worse.

📖 Answer

@Entity
@DynamicUpdate
class Account {
    @Id Long id;
    String fullName;
    String address;
    @Lob String notes;
    BigDecimal balance;
}

After account.setBalance(...):

-- without @DynamicUpdate
update account set address=?, balance=?, full_name=?, notes=? where id=?
-- with @DynamicUpdate
update account set balance=? where id=?

When it helps:

  • the table is wide (dozens of columns, or big text/bytea) and usually one or two fields change: network and WAL volume go down;
  • without @Version, if two transactions change different columns of the same row, a full UPDATE overwrites one's change with the old value, while with a dynamic UPDATE each writes only its own column;
  • when a database trigger or CDC should see only the columns that really changed.

The cost:

  • the SQL for each UPDATE is built at runtime, so the PreparedStatement cache works less;
  • UPDATEs with different column sets don't merge into one JDBC batch.

We have to be honest on the second point: the main protection against lost updates is still @Version. @DynamicUpdate helps only when the columns differ; if two people change the same column, the last one wins.

I don't turn it on by default for every entity: on an average table the difference isn't noticeable. I enable it where I've measured a benefit.