Video in progress
How does dirty checking work internally, and why does it get slow in a big persistence context?
On load, Hibernate stores a state array (snapshot) for each entity, and on flush it compares every field of every managed entity against that snapshot. With 50 thousand entities in the context, every flush means that many comparisons, plus double the memory.
📖 Answer
Without bytecode enhancement, Hibernate has no other way of knowing "what changed": it walks over everything. On flush it goes roughly like this:
- Each entity in the persistence context is taken.
- Its current fields are collected into an
Object[]. - Each field is compared with the snapshot value using the type's
equals. - If they differ, an UPDATE action is put in the queue.
In AUTO mode this can happen before every JPQL query as well. In a big transaction that sends queries inside a loop, the flushes themselves eat a large share of the CPU, and DefaultFlushEntityEventListener shows up at the top of the profiler.
What I do:
readOnly = truefor reads: no snapshot is taken at all.- In bulk processing, keep the context small with
flush()+clear(). - Turn on bytecode enhancement with dirty tracking: the entity itself records which field changed, so no comparison is needed.
- Be careful with mutable types:
Date, arrays, custom types for JSON fields. A wrongequalson them looks "changed" on every flush and produces needless UPDATEs.
One more subtle point: by default the UPDATE writes all columns, not only the changed one. That's good for statement caching, but on a wide table, or when the columns have triggers, @DynamicUpdate helps:
@Entity
@DynamicUpdate // UPDATE with only the changed columns
public class Profile { ... }
Sign up to mark studied questions and save your progress.