Dirty checking lets JPA and Hibernate update a managed entity without an explicit update call. Load an entity into an EntityManager’s persistence context, change its state inside a transaction, and Hibernate detects the change when it flushes. The persistence context monitors managed entities and synchronizes their state with the database. section 2.3.3 section 10.1.2
Change a managed entity
After beginning a transaction: `Item item = em.find(Item.class, ITEM_ID); item.setName("New Name"); em.getTransaction().commit();` No update method is needed. Hibernate compares the managed Item with a snapshot taken when it was loaded and issues an SQL UPDATE if its persistent state changed. section 10.2.3 section 10.2.1
Flushing determines when detected changes reach the database:
- A transaction commit triggers dirty checking and synchronization. `em.flush()` forces them earlier within the transaction. section 10.2.1
- With the default `FlushModeType.AUTO`, Hibernate may flush before a query so it sees earlier changes. `FlushModeType.COMMIT` defers that flush; a query can then return a database value different from the value held in memory. section 10.2.9
Snapshot checking costs memory and time: Hibernate retains snapshots and may compare every managed instance during a flush. Its default UPDATE includes all mapped columns, even unchanged ones; dynamic SQL generation can instead target modified columns. Keep queries and persistence contexts from retaining more entities than the unit of work needs. section 10.2.3 section 10.2.8
Accessor methods and collection mappings affect what counts as a change. For an ordinary property, Hibernate compares values rather than object identity, so a getter returning a new but equal value need not cause an UPDATE. Replacing an entire collection through a setter can cause an unnecessary UPDATE because Hibernate uses its own persistent collection implementations. section 3.2.3
For data that must not be updated, an entity mapped with Hibernate’s `@Immutable` can avoid dirty checking. Read-only settings can disable snapshots and checking for a persistence context, an individual entity, or query results. A modified read-only entity will not be updated on flush; mapped collections require extra care. section 5.3.3 section 10.2.8
