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.
A service returns an `Order`, and the controller calls `order.getLines()` and gets `LazyInitializationException: could not initialize proxy - no Session`. One teammate suggests making `lines` EAGER; another says just keep `spring.jpa.open-in-view=true`. What is the exception actually telling you, and what is the right fix?A long-running `@Transactional` job loads an `Account`, does some work, then re-runs a JPQL query for the same account "to get the latest balance" — the SQL shows in the log — and changes its `status`. Meanwhile another request committed a new balance. After the job commits, that other request's balance change is gone. Explain every step, and how `@Version` changes the outcome.