Repaso
EspaƱol

What is the persistence context and what is "dirty checking"?

Options

  1. A log file where the database records its changes
  2. A per-transaction entity cache; changes saved at commit (Correct option)
  3. A security feature that limits who can read an entity
  4. A way to copy tables from one database to another

Answer

A per-transaction cache of managed entities; at commit, JPA compares them with their original state and issues UPDATEs automatically for changed ones, even without calling save

Why

When you load an entity inside a transaction, JPA keeps it in a persistence context (first-level cache) and remembers its original values. This entity is "managed".

If you call a setter on a managed entity, then at flush/commit JPA detects the difference (dirty checking) and runs the UPDATE itself. So inside a @Transactional method, user.setName("x") is enough; save() is not required.

The same findById twice in one transaction also returns the same object without hitting the database again.

Remember

Managed entities are auto-saved at commit when changed.

Key terms

Practice this question in Repaso