Persistence contexteasy0-2 years

A `@Transactional` service method loads an `Author`, calls `setName(...)`, and returns. There is no `save()` anywhere, yet the log shows `update Author set name=? where id=?`. Where did that UPDATE come from, and is adding `repository.save(author)` "to be safe" a good idea?

The entity is managed: it was loaded inside a transaction, so it sits in that transaction's persistence context, and Hibernate kept a snapshot of the row as it looked when it was loaded. When the transaction ends, Hibernate flushes: it compares every managed entity against its snapshot, finds that name differs, and writes an UPDATE for it. That comparison is dirty checking, and it is how updates normally happen in JPA. Adding save() on an entity you just loaded in the same transaction is not wrong, but it is redundant, and it teaches the wrong model: it makes people believe nothing is written without it, which is exactly the belief that gets them surprised when a change they made in a method they thought was read-only is written anyway.

The lesson behind it →
More on Persistence context