Video in progress
What does `@DynamicUpdate` do, and when does it make sense to turn it on?
By default Hibernate writes all of the entity's columns in an UPDATE. With @DynamicUpdate, only the changed columns go into the SQL. It helps with wide tables, large columns, and when two parallel transactions change different fields, but it can hurt the statement cache and batching.
📖 Answer
The usual case:
-- only status changed, but:
update product set name=?, description=?, price=?, status=?, stock=?, version=? where id=? and version=?
Hibernate prepares this once at startup and uses that SQL for every instance of the entity. The advantage: the SQL text is a single one, so the database's prepared statement cache and JDBC batching work well.
With @DynamicUpdate:
@Entity
@DynamicUpdate
class Product { ... }
update product set status=?, version=? where id=? and version=?
When it's worth it:
- the table has 40-50 columns and usually only one or two change;
- there's a big
text/jsonbcolumn, and rewriting it every time makes WAL and replication heavier; - on an entity without a version, two processes change different fields: a full UPDATE lets one overwrite the other's change, while with a dynamic update each writes only its own column;
- if you use
@OptimisticLocking(type = DIRTY), it doesn't work without@DynamicUpdate.
The cost: a separate SQL statement is generated for each combination of columns, and UPDATEs that arrive in a row in a batch don't get grouped if they differ. That's why I don't put it on every entity, only on tables that have the reasons above.
Sign up to mark studied questions and save your progress.