Video in progress

How does dirty checking work in Hibernate?

When an entity becomes managed, Hibernate keeps a copy (a snapshot) of its state as it was loaded. On flush it compares the current fields to the snapshot and, if they differ, sends the UPDATE itself. You don't need to call save().

📖 Answer

@Transactional
public void rename(Long id, String name) {
    Product p = repo.findById(id).orElseThrow();
    p.setName(name);
    // no save(): the flush before commit sends the UPDATE automatically
}

Many new developers write repo.save(p) here. It isn't wrong, but it's pointless: for a managed object save calls merge, which changes nothing.

Things you should know:

  • by default the UPDATE writes all columns, not just the changed ones. If you want only the changed ones, use @DynamicUpdate;
  • the snapshot takes memory: for every loaded entity a second copy of its fields is stored;
  • on flush Hibernate walks over every entity in the context. With 100 thousand objects in the context, flush gets noticeably slower.

If you put @Transactional(readOnly = true) on read-only methods, Hibernate doesn't keep snapshots and skips this check.