Video in progress
After the method below is called, does the user's name change in the database?
@Service
public class UserService {
private final UserRepository repo;
@Transactional
public void rename(Long id, String newName) {
User user = repo.findById(id).orElseThrow();
user.setName(newName);
}
}
Yes, it does. The entity was loaded inside the transaction, so it is managed, and dirty checking finds the change before commit and sends the UPDATE itself. save() isn't needed.
📖 Answer
The sequence goes like this:
@Transactionalopens a transaction and a persistence context.findByIdsends a SELECT,userbecomes managed, and its snapshot is saved.setNameonly changes the Java object.- When the method ends, Spring commits; before the commit Hibernate flushes, compares with the snapshot, and sends
update users set ... where id=?.
There are cases where the answer is "no", and it's good to mention them in an interview:
- if
@Transactionaldoesn't kick in: the method isprivate, or it is called asthis.rename(...)from within the same class. The proxy is bypassed, the entity is loaded without a transaction and ends up detached; - if it's
@Transactional(readOnly = true), Hibernate doesn't flush; - if an exception is thrown inside the method and the transaction rolls back;
- if the
namefield is@Column(updatable = false).
In practice, not knowing this behavior also causes bugs like "why did something I never saved get written to the database?", for example when someone changes an entity's field for convenience before turning it into a DTO.
Sign up to mark studied questions and save your progress.