Skip to content
javahacks.dev
Hibernate

Hibernate Dirty Checking and How Updates Really Happen

How Hibernate dirty checking decides which entities to UPDATE at flush: snapshots, comparison cost, DynamicUpdate and bytecode enhancement.

7 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, OpenJDK, PostgreSQL and MariaDB logos.

You load a Customer, call a getter in a logging statement, and the database receives an UPDATE you never asked for. Or you call a setter, never call save, and the change is written anyway. Both surprise people who think of Hibernate as a library that runs SQL when told to. A managed entity is different: Hibernate watches it, compares it with a snapshot at flush time and writes whatever differs. That mechanism is dirty checking, and understanding it explains the unexpected updates, the cost of loading many entities, the effect of @DynamicUpdate and bytecode enhancement, and why optimistic locking is a natural companion. This post follows one entity through a transaction with SQL logging on, shows the three kinds of surprise, measures what dirty checking costs, and covers the tools that change it. Examples use Hibernate 7 and Spring Boot 4.

The mechanism

When Hibernate loads an entity into a persistence context, it keeps two things: the entity instance you work with, and a snapshot, a copy of its persistent field values at load time. At flush time (before a query that could be affected, and at commit) Hibernate walks every managed entity, compares its current state to the snapshot, and for each difference schedules an UPDATE. No call to save or merge is involved. The entity is managed, so its changes are tracked.

Watch it happen. With SQL logging on (spring.jpa.show-sql=true), a service that only changes a field:

src/main/java/dev/javahacks/shop/CustomerService.javajava
@Service
class CustomerService {

    private final CustomerRepository customers;

    CustomerService(CustomerRepository customers) {
        this.customers = customers;
    }

    @Transactional
    public void rename(long id, String name) {
        Customer c = customers.findById(id).orElseThrow();
        c.setName(name);                    // no save() call
    }
}
Text
select c1_0.id,c1_0.email,c1_0.name from customer c1_0 where c1_0.id=?
update customer set email=?,name=? where id=?

The update appears because the transaction committed with a managed entity whose name differs from its snapshot. Note the statement sets every column, email as well as name, a default that matters later. Remove @Transactional and the same method does nothing: the entity is detached as soon as the repository call returns, so nobody watches it. This is why save() on an already managed entity is redundant: it has nothing to add. The managed and detached states, and what moves an entity between them, are laid out in Hibernate entity states and the persistence context.

Why unexpected updates occur

Because tracking is automatic, anything that changes a managed entity's fields counts, deliberately or not.

A getter with a side effect. The classic: a getter normalizes or defaults a value.

java
public String getEmail() {
    if (email == null) {
        email = "";            // mutates state inside a getter
    }
    return email;
}

Loading a customer with a NULL email and merely calling getEmail() makes the entity dirty, and the next flush writes an empty string. Keep getters pure.

Mutable field types that compare as changed. Hibernate compares fields with equals, or for mutable types by a value copy. A Date, an array or a collection field whose contents are reordered looks changed even if logically equal. An @Embeddable without a proper equals is compared by reference and reports a change every time. A BigDecimal loaded with scale 2 and set to a new BigDecimal("10.0") differs in scale and compares unequal in equals.

Normalizing in a setter or callback. A @PreUpdate or setter that trims or lower-cases changes the value to something different from what was loaded, producing an update for data nobody edited.

Conversion round trips. An AttributeConverter that does not produce the same value it reads (a JSON column serialized with a different key order) is dirty on every load.

A flush at the wrong time. Hibernate's auto flush mode flushes before a query that touches affected tables, so a change you made earlier gets written in the middle of your method, before you intended; the flush rules are in flush modes and the first-level cache and the auto flush section of the user guide.

Find unexplained updates with the SQL log and the statistics: turn on hibernate.generate_statistics and read the entity update counts, as covered in debugging Hibernate SQL behavior. A stack trace for the flush shows who changed what, which narrows it to a field.

Cost

Dirty checking is a comparison per field per managed entity at every flush. For ten entities it is invisible. For a batch job that loads 100,000 entities in one transaction it is real work and real memory: the persistence context holds the instance and its snapshot, and each flush compares them all. The flush time and heap use grow with the number of managed entities, which is why long batch loops that never clear the context slow down as they go. A rough way to see it:

java
for (int i = 0; i < 50_000; i++) {
    Customer c = new Customer("name-" + i);
    em.persist(c);
    if (i % 500 == 0) {
        em.flush();
        em.clear();          // detach everything: the next flush compares nothing
    }
}

Flush and clear every few hundred entities, so the persistence context stays small. The same applies to reads that you only display: if you will not change the entities, do not pay to track them. Mark the transaction read-only (Spring sets the flush mode to manual, so no dirty checking occurs, see using Transactional readOnly correctly) or read DTO projections that are not entities at all, which carry no snapshot and no tracking.

DynamicUpdate

By default, Hibernate generates the UPDATE statement for an entity once, setting every column, whichever field changed. This is efficient because the statement can be cached and prepared, and wasteful for wide tables and tools that audit column writes. @DynamicUpdate makes Hibernate build the statement per update, with only the changed columns:

java
@Entity
@DynamicUpdate
class Customer {
    @Id Long id;
    String name;
    String email;
    // ...
}
Text
update customer set name=? where id=?

The trade-offs: the SQL is generated at each update (a small CPU cost and more distinct statements, which hurts statement caching and batching), and the benefit is narrower writes, less lock scope in some databases and a clearer audit. It also matters for concurrency: with the default full-row update, two transactions changing different columns of one row overwrite each other's changes, because each writes its stale copy of the unchanged columns. @DynamicUpdate writes only what each changed, which avoids that lost-update variant for disjoint fields, though not for the same field. Use it for wide tables, for rows with large columns (a blob you do not want rewritten on every change) and when concurrent writers touch different fields.

Bytecode enhancement

The snapshot comparison is the default strategy and not the only one. With bytecode enhancement, a Maven or Gradle plugin changes your entity classes at build time so that they track their own changes: each setter marks the field dirty, and Hibernate asks the entity which fields changed instead of comparing everything. The configuration for the Maven plugin:

pom.xmlXML
<plugin>
  <groupId>org.hibernate.orm</groupId>
  <artifactId>hibernate-maven-plugin</artifactId>
  <version>${hibernate.version}</version>
  <executions>
    <execution>
      <phase>compile</phase>
      <goals><goal>enhance</goal></goals>
      <configuration>
        <enableDirtyTracking>true</enableDirtyTracking>
        <enableLazyInitialization>true</enableLazyInitialization>
      </configuration>
    </execution>
  </executions>
</plugin>

Dirty tracking removes the comparison cost and the snapshot memory, so large persistence contexts flush faster. Lazy initialization at field level (lazy basic attributes) also comes with enhancement. The cost is a build step, a closer coupling between your classes and Hibernate, and subtle bugs if the plugin does not run for some module or the tests. Reach for it when a profile shows flush time dominated by dirty checking on large contexts; for most services, flushing and clearing in batches is simpler. The details are in the bytecode enhancement chapter of the user guide.

Optimistic locking

Dirty checking decides what to write; it does not decide whether writing is safe. Two users load the same row, both change it and both flush, and the second UPDATE overwrites the first silently. Optimistic locking adds a version column that every update checks:

java
@Entity
class Customer {
    @Id Long id;
    @Version long version;
    String name;
}
Text
update customer set name=?,version=? where id=? and version=?

If another transaction changed the row since you loaded it, the where version=? matches nothing, zero rows update and Hibernate throws an OptimisticLockException (Spring translates it to ObjectOptimisticLockingFailureException). The caller then reloads and retries or reports a conflict. The failure and how to handle it are in fixing StaleObjectStateException and locking failures. The combination is the usual recommendation: dirty checking for convenience, a version column for safety, and @DynamicUpdate where columns are wide or independent.

Where this does not apply

For entities loaded outside a transaction and never reattached, there is no tracking, and changes are lost unless you merge. A stateless session (StatelessSession) skips the persistence context entirely, with no snapshots, no dirty checking and no first-level cache, which is the right tool for large bulk operations. Bulk JPQL or HQL updates (update Customer set ...) bypass the context too, so any managed instances become stale. And if you use Spring Data JDBC or jOOQ, there is no dirty checking: you write what you mean.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.